Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 701
Aishwar Avatar asked Aug 26 '10 22:08

Aishwar


People also ask

Does setTimeout execute immediately?

JavaScript has setTimeout() method which calls a function or evaluates an expression after a specified number of milliseconds.

What happens when setTimeout is 0?

Invoking setTimeout with a callback, and zero as the second argument will schedule the callback to be run asynchronously, after the shortest possible delay - which will be around 10ms when the tab has focus and the JavaScript thread of execution is not busy.

Does setTimeout stop execution?

No, setTimeout does not pause execution of other code.

How can you delay the execution of the function?

To delay a function call, use setTimeout() function. functionname − The function name for the function to be executed. milliseconds − The number of milliseconds. arg1, arg2, arg3 − These are the arguments passed to the function.


1 Answers

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/

like image 194
angusC Avatar answered Sep 22 '22 18:09

angusC