views:

111

answers:

3

I am looking at some existing code in a web application. I saw this:

window.setTimeout(function () { ... })

Is this the same as just executing the function content right away?

+5  A: 

There is a minimum delay that setTimeout uses (4ms as per HTML5, Firefox 3.6 uses 10ms). There is a discussion about it on the Mozilla Developer Center documentation page. Everything I can find specifies that the delay parameter is required, but I don't get an error (or even a strict warning) without it (in firefox). My best guess is that the minimum is used in that case.

Daniel Vandersluis
+1  A: 

You are missing the millisecond parameter...

setTimeout(function() { //something }, 0);

The 0 sets the delay to 0 but what it actually does is to let your function "jump the queue" of the browser execution list. The browser has a bunch of things to do such as rendering objects on the page, and by calling this, your function will run as soon as the browser has some cycles.

Gary
This is the question...the title's asking what happens when there is no delay provided :)
Nick Craver
Oh okay. I thought it was a syntax error as various documents state it is a required parameter. Then I tried it out quickly and it worked.
Gary
+1: Thats a cool insight on the reason to do this - "jump the queue" of the browser
aip.cd.aish
+1  A: 

It won't necessarily run right away, neither will explicitly setting the delay to 0. The reason is that seTimeout removes the function from the execution queue and it will only be invoked after JavaScript has finished with the current execution queue.

console.log(1);
setTimeout(function() {console.log(2)});
console.log(3);
console.log(4);
console.log(5);
//console logs 1,3,4,5,2

for more details see http://javascriptweblog.wordpress.com/2010/06/28/understanding-javascript-timers/

angusC
+1 Good link. Nice example.
aip.cd.aish