jQuery setTimeout() Function Examples

The JavaScript 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.

See the Pen CSS3 animation effects for Magnific Popup by SitePoint (@SitePoint) on CodePen.

Syntax

From the MDN documentation, the syntax for setTimeout is as follows:

[code language=”js”]
var timeoutID = window.setTimeout(func, [delay, param1, param2, …]);
var timeoutID = window.setTimeout(code, [delay]);
[/code]

where:

  • 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.

Powered by WPeMatico

The featured image was randomly selected. It is an unlikely coincidence if it is related to the post.