setTimeout function calls a function or executes a code snippet after a specified delay (in milliseconds). This might be useful if, for example, you wished to display a popup after a visitor has been browsing your page for a certain amount of time, or you want a short delay before removing a hover effect from an element (in case the user accidentally moused out).
Basic setTimeout Example
To demonstrate the concept, the following demo displays a popup, two seconds after the button is clicked.
From the MDN documentation, the syntax for
setTimeout is as follows:
var timeoutID = window.setTimeout(func, [delay, param1, param2, …]);
var timeoutID = window.setTimeout(code, [delay]);
timeoutIDis a numerical id, which can be used in conjunction with
clearTimeout()to cancel the timer.
funcis the function to be executed.
code(in the alternate syntax) is a string of code to be executed.
delayis the number of milliseconds by which the function call should be delayed. If omitted, this defaults to 0.
setTimeout vs window.setTimeout
You’ll notice that the syntax above uses
window.setTimeout. Why is this?
window.setTimeout are essentially the same, the only difference being that in the second statement we are referencing the
setTimeout method as a property of the global
In my opinion this adds complexity, for little or no benefit—if you’ve defined an alternative
setTimeout method which would be found and returned in priority in the scope chain, then you’ve probably got bigger issues.
For the purposes of this tutorial, I’ll omit
window, but ultimately which syntax you chose is up to you.