Alex Rivera | Logout

Is setTimeout with no delay the same as executing the function instantly?

Asked 2010-08-26T22:29:54.583
59

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?

Edit
Report

1 Answer

105

It won't necessarily run right away, neither will explicitly setting the delay to 0. The reason is that setTimeout 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/

answered 2010-08-27T01:22:05.867

Your Answer