开发者

setTimeout callback gets "random number" as parameter?

开发者 https://www.devze.com 2023-02-18 06:33 出处:网络
Today, I was making a loop with a setTimeout(). Unfortunately, some function parameters were getting strange values.

Today, I was making a loop with a setTimeout(). Unfortunately, some function parameters were getting strange values.

In short, this is what's happening:

var x = 1;
v开发者_如何学Pythonar steps = 3;
var timer = false;

function myFunc( y ){
   if( !isNaN(y)&&parseInt(y)==y&&y>0 ) { // if y is int and greater than 0
     x = y;
   } else { // y is no int or is below 0
     if( x >= steps ) { // x is greater than or equal to steps, return to first step
      x = 1
     } else { // x is less than steps, add 1
      x++;
     }
   }

   window.clearTimeout( timer );

   timer = setTimeout( myFunc, 1000 );
}

Now, somehow Mr. Firefox is randomly throwing an int, far greater than "steps" into the "y" parameter while triggering the timer... WHY does it do that?

I've resolved this problem by simple doing this:

timer = setTimeout( function(){ myFunc( -1 ) }, 1000 );

But still... WHY was the browser giving random numbers in the "y" parameter?

Anyone?


Firefox will call the function with the number of milliseconds "late" the function is in executing.


As a protip, you can also just use setInterval to achieve the same basic functionality:

var x = 1;
var steps = 3;
var timer = false;

function myFunc( y ){
    if (parseFloat(y) == parseInt(y) && !isNaN(y) && y > 0) {
        x = y;
    } else if (x >= steps) {
        x = 1;
    } else {
        x++;
    }
}


timer = window.setInterval(function() { 
    myFunc(1); 
}, 1000);


Note: Gecko passes an extra parameter to the callback routine, indicating the "lateness" of the timeout in milliseconds.

Source : https://developer.mozilla.org/en/DOM/window.setTimeout#Syntax

Infinite loop?

var x = 0,
steps = 3,
timer = false;

(function myFunc(y)
{
    x = y % steps;

    timer = setTimeout(myFunc, 1000, ++x);
})(0);
0

精彩评论

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