开发者

What does the function given to setTimeout get called with?

I have code like this:

setTimeout(foo, 600);

I always thought that foo didn't take any argument开发者_运维百科s, e.g.:

function foo() { /* bars */ }

However, doing the following:

function foo(a) { alert(a); /* bars */ }

Popped up an alert displaying -7. What does this number represent?


It is the time difference (in milliseconds) from when it was scheduled to run it and when it actually ran.

alert(setTimeout(function(a) { alert(a) }, 2000));

If you clear the first alert in time, you will see the next alert is somewhere -10 to 10. If you wait a few seconds, you will see something that is around the time you waited minus 2000.

The same thing can be seen for setInterval. Run the following in Firebug:

setInterval(function(a) { alert(a); }, 2000);

Try closing the alert quick, it will be around 0 again. Leave it open - it will give you a large value.

Note This is on Firefox Mac, where keeping an alert open will halt processing of Javascript, so the timer does not execute until I close the alert. The behavior of the tests above may be different in other browsers


From what I can tell... the argument in the difference between when it was scheduled and when it actually ran in milliseconds. Interestingly enough, seems certain browsers like even fractions of whole seconds...

<script>
var a = setInterval(foo, 125);

console.log(a);

function foo(b) {
 console.log(b);
}
</script>

will output a bunch of zeros, same goes for 250, 500, 1000... while

<script>
var a = setInterval(foo, 127);

console.log(a);

function foo(b) {
 console.log(b);
}
</script>

will output

 -2
12
-6
8
-10
4
2
0
-2
-4
9
-8
5
3
1
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜