views:

80

answers:

2

I have code like this:

setTimeout(foo, 600);

I always thought that foo didn't take any arguments, 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?

+6  A: 

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

Renesis
yep.. it is documented in a very minor way here: https://developer.mozilla.org/en/DOM/window.setTimeout . looks like it's a firefox-only thing
Claudiu
Quite a clever feature, shame IE doesn't have it too. Then again it's a shame IE doesn't have a lot of things :-)
Andy E
@Andy E If you look at https://bugzilla.mozilla.org/show_bug.cgi?id=394769 it seems there is quite a controversy over its existence at all, since it reduces the usability of functions with optional arguments being called by setTimeout.
Renesis
@Renesis: A very good point. A check for `arguments.caller == null` would seem like the most appropriate workaround in that situation. It does look like it might be removed soon to be HTML5 compliant, however.
Andy E
+1  A: 

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
Mike Sherov