Basic setTimeout Example
To demonstrate the concept, the following demo displays a popup, two seconds after the button is clicked.
See the Pen CSS3 animation effects for Magnific Popup by SitePoint (@SitePoint) on CodePen.
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]);
timeoutID is a numerical id, which can be used in conjunction with clearTimeout() to cancel the timer.
func is the function to be executed.
code (in the alternate syntax) is a string of code to be executed.
delay is 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?
Well, setTimeout and 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 window object.
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.
The post jQuery setTimeout() Function Examples appeared first on SitePoint.