How to Use setTimeout() in jQuery
In today’s post, we’ll learn about the setTimeout()
function in jQuery.
Use setTimeout()
in jQuery
The setTimeout()
method sets a timer to execute a function or targeted piece of code once the timer expires. The setTimeout()
function of JavaScript postpones certain actions or code execution in that function or at another JS function.
This function is always executed with the time delay specified in milliseconds.
Syntax:
setTimeout(code, delay)
setTimeout(functionRef, delay, param1)
- The
functionRef
is a function that will complete after the timer expires. - The
code
is an alternative syntax that allows you to insert a string instead of a function that will be compiled and executed when the timer expires. This syntax is not recommended for the same reasons that make usingeval()
a security threat. - The
delay
is an optional parameter that specifies the time, in milliseconds, that the timer should wait before completing the required function or code. If this parameter is left out, a value of 0 is used, meaning the code will execute immediately. - The
param1, ... , paramN
is an optional parameter. It specifies extra arguments passed through to the function defined byfunctionRef
.
The setTimeout()
function returns timeoutID
which is a positive integer value; this value identifies the timer created by calling setTimeout()
function. To cancel the timeout, you can pass this parameter to clearTimeout()
.
A value of timeoutID
is guaranteed never to be reused by a subsequent call to setTimeout
or setInterval
on one element within a window or worker. However, one-of-a-kind items use separate pools of IDs.
Not only is this function used in local JavaScript, but you can also use setTimeout()
in jQuery. To delay motion, you could use the setTimeout()
function inside the jQuery code.
Let’s understand it with the following example:
$(document).ready(function() {
setTimeout(() => {
alert('Welcome to DelftStack!');
}, 2000);
});
In the above example, we are using setTimeout()
to display an alert by an interval of 2000 milliseconds.
Attempt to run the above code snippet in any browser that supports jQuery. It’s going to display the result shown below.
Output:
View the demo here.
Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.
LinkedIn