开发者

Can setInterval store a value in a variable

开发者 https://www.devze.com 2023-02-01 00:15 出处:网络
Look at this code var count = 0, count2 = 0 setInterval(function() { // I wrote this on two lines for clarity.

Look at this code

var count = 0, count2 = 0
setInterval(function() {
    // I wrote this on two lines for clarity.
    ++count;
    count2 = count;
}, 10开发者_运维百科00);
if(count2==5)
{
alert('testing script')
}

How come the if statement does not execute when count2 = 5


The problem is: First you only define the logic for the interval and then you check the count2 variable. But in that context the variable has still the value 0.

Each time the interval is fired (and in most cases it is after the if-check), only the part inside the function() { } block is executed

function() {
    // I wrote this on two lines for clarity.
    ++count;
    count2 = count;
}

and it is not continued to the if statement because it is not part of the interval logic.

The first idea I have is to put the if statement into the function() { } block like this:

var count = 0, count2 = 0;

setInterval(function() {

    // I wrote this on two lines for clarity.
    ++count;
    count2 = count;

    if(count2 == 5)
    {
        alert('testing script');
    }

}, 1000);


var count = 0, count2 = 0 // missing semi colon(!)
setInterval(function() { // this function will be executed every 1000 milliseconds, if something else is running at that moment it gets queued up
    ++count; // pre-increment count
    count2 = count; // assign count to count 2
}, 1000);

// ok guess what this runs IMMEDIATELY after the above, and it only runs ONCE so count 2 is still 0
if(count2==5) // DON'T put { on the next line in JS, automatic semi colon insertion will get you at some point
{
    alert('testing script')
}

Read a tutorial to get started: https://developer.mozilla.org/en/JavaScript/Guide.


yes it can store a value.

function hello(){
    var count = 0;
    var timer = setInterval( function(){  count+=1;alert(count); },2000);
}


Try This Out, it works

//Counting By Z M Y.js
if(timer){window.clearInterval(timer)} /*← this code was taped , in order to avoid a sort of bug , i'm not going to mention details about it  */
c=0; 
do{   w=prompt('precise the number of repetition in which the counting becomes annoying',10)} 

                                    while (!(w>0)||w%1!=0)
   function Controling_The_Counting(c,w)
   {
if(c%w==0&&c>0){return confirm('do you want to continue ?'); }
return true;
   } 

    var timer = setInterval( function(){  console.clear();c+=1;console.log(c); StopTimer()  },1000);
  function StopTimer() {  if(!Controling_The_Counting(c,w)) {window.clearInterval(timer) ;} }
0

精彩评论

暂无评论...
验证码 换一张
取 消