Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What the difference between window.setTimeout() and setTimeout()?

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?

like image 521
user3073240 Avatar asked Dec 06 '13 09:12

user3073240


People also ask

What is the difference between setImmediate () and setTimeout ()?

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.

What does the window setTimeout method do?

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);


2 Answers

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.

like image 92
Oswald Avatar answered Sep 19 '22 10:09

Oswald


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.

like image 35
Madara's Ghost Avatar answered Sep 17 '22 10:09

Madara's Ghost