Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the function given to setTimeout get called with?

Tags:

javascript

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?

like image 202
Claudiu Avatar asked Feb 18 '10 23:02

Claudiu


1 Answers

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

like image 131
Nicole Avatar answered Oct 04 '22 14:10

Nicole