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?
JavaScript has setTimeout() method which calls a function or evaluates an expression after a specified number of milliseconds.
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.
No, setTimeout does not pause execution of other code.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With