I would like to know what the difference is between
window.setTimeout(myFancyFunciton, 1000);
and
setTimeout(myFancyFunciton, 1000);
Both seem to do the exact same thing. When should you use one or the other?
setImmediate() vs setTimeout()setImmediate() is designed to execute a script once the current poll phase completes. setTimeout() schedules a script to be run after a minimum threshold in ms has elapsed.
The setTimeout() method executes a block of code after the specified time. The method executes the code only once. The commonly used syntax of JavaScript setTimeout is: setTimeout(function, milliseconds);
JavaScript runs in an environment that is defined by a global object. Methods of the global object can be called without explicitly refering to the object (i.e. without the obj.function()
notation).
When you run JavaScript inside the browser, the global object is provided by the Document Object Model (DOM). The global object of the DOM has a method setTimeout()
. That's why you can call setTimeout()
.
The DOM specifies that the global object has a property named window
, which is a reference back to the global object. That's why you can call window.setTimeout()
and (by transitivity) window.window.setTimeout()
, window.window.window.setTimeout()
, and (you guessed it) window.window.window.window.window.window.window.window.window.setTimeout()
. It's all the same method of the same object.
Assuming we're talking about browser-based JavaScript: No difference. setTimeout()
simply omits the window.
, which is implied. The effect they have is exactly the same.
It's a choice of coding style and preference.
For JavaScript that does not run in a browser, the window
object is not defined, so window.setTimeout()
will fail. setTimeout()
however, will work.
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