setTimeout
is a native JavaScript function (although it can be used with a library such as jQuery, as we’ll see later on), which 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).
This popular article was updated in 2020.
Basic setTimeout Example
To demonstrate the concept, the following demo displays a popup, two seconds after the button is clicked.
See the Pen Delayed Magnific Popup modal by SitePoint (@SitePoint) on CodePen.
If you don’t see the popup open, please visit CodePen and run the demo there.
Syntax
From the MDN documentation, the syntax for setTimeout
is as follows:
var timeoutID = scope.setTimeout(function[, delay, arg1, arg2, ...]);
var timeoutID = scope.setTimeout(function[, delay]);
var timeoutID = scope.setTimeout(code[, delay]);
where:
timeoutID
is a numerical ID, which can be used in conjunction with clearTimeout to cancel the timer.scope
refers to the Window interface or the WorkerGlobalScope interface.function
is the function to be executed after the timer expires.code
is an alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires.delay
is the number of milliseconds by which the function call should be delayed. If omitted, this defaults to 0.arg1, ..., argN
are additional arguments passed to the function specified byfunction
.
Note: the square brackets []
denote optional parameters.
setTimeout vs window.setTimeout
You’ll notice that the syntax above uses scope.setTimeout
. Why is this?
Continue reading JavaScript setTimeout() Function Examples on SitePoint.
No comments:
Post a Comment