Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
2.
What is the setTimeout() Method?
2.1.
Syntax of setTimeout jQuery
2.2.
Return type
3.
Working of settimeout jQuery
4.
Example of setTimeout jQuery
5.
setInterval() Method
5.1.
Syntax
5.2.
Example
6.
clearTimeout() Method
6.1.
Syntax
6.2.
Example
7.
Frequently Asked Questions
7.1.
What is the use of setTimeout in jQuery?
7.2.
How does setTimeout () work?
7.3.
What does the setTimeout () return?
7.4.
How to call a function with timeout in jQuery?
8.
Conclusion
Last Updated: Mar 27, 2024
Medium

How to use jQuery setTimeout?

Author Sohail Ali
1 upvote
gp-icon
Basics of javascript
Free guided path
10 chapters
68+ problems
gp-badge
Earn badges and level up

Introduction 

Hey coders, you must know how useful the jQuery library is while we write Javascript code. If not, then you can learn the basics of jQuery from our website. So jQuery is a lightweight Javascript library that provides various functions to Javascript for writing code simpler and easier. You can refer to our website jQuery vs. Javascript, to understand the difference between these two.

How to use jQuery setTimeout?

Once you know the basics of JQuery, we can start our journey. So in this blog, we will see how to use jQuery setTimeout() with some examples. So tighten your seatbelt, and let’s get started.

What is the setTimeout() Method?

Whenever we want some piece of program to run after some period of time, the setTimeout() function in Javascript can help us achieve that. This function works smoothly with jQuery without putting in any extra effort. 
It is useful to delay some programs/events in jQuery and is very useful whenever we want the execution of the program to be halted for some time.

Syntax of setTimeout jQuery

setTimeout (function, milliseconds);


Here, the function represents the name of the function that will be executed after ‘milliseconds’ time has elapsed. 

Note: The setTimeout() function is executed only once. By calling the clearTimeout() function, we can stop the execution of the function. 

Return type

This function returns the id of the timer whenever the ‘function’ begins executing.

Note: We can use this timer id to stop the execution with the help of the clearTimeout() function by passing the id as a parameter.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Working of settimeout jQuery

Let us understand the working of settimeout() in jQuery.

  • First, you provide two arguments for it. One is the function or the code you want to execute after the delay. And the second is the delay duration in milliseconds.
     
  • Then, when you call the settimeout() function, the timer starts to count down the passed delay duration.
     
  • Once the specified time duration is passed, the code block or the function is added to the JavaScript event queue.
     
  • Finally, the function gets executed.
     

You can see it working with the help of an example below.

Example of setTimeout jQuery

Now, let’s write a code in which whenever we click on a Hide button, the contents with that id should fade out after some interval.

<!DOCTYPE html>
<html> 
    <head>
        <!-- Tittle  -->
        <title>setTimeout</title>
    </head>  
    <body>
        <section>
            <div >
                <!-- Heading -->
                <h1>setTimeout in jQuery</h1>
                <div>
                    <!-- Creating the hide button -->
                    <button  id="Hide_button">Cover the Logo </button><br>
                    <br> <br>

                    <!-- Including logo image -->
                    <img src="fig.png" id="CodingNinjas_Logo" width="250px">
                </div>
            </div>
        </section>
        
        <!-- JQuery -->
        <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
        <script>
            $(document).ready(function() { 
                $("#Hide_button").bind("click",function() {
                  setTimeout(function() { 
                    $('#CodingNinjas_Logo').fadeOut();}, 2000); 
              });
            });
        </script>
    </body>
</html> 


Output

settimeout method

Explanation

In the above example, we created a basic button with the id Hide_button which is then passed to the function. Whenever this button is clicked, the fadeOut() is called for the logo, and after 2000 milliseconds/2 seconds, the logo will fade away. 

After 2 seconds, the resultant output will be:

setTimeout output

If we click the button, the setTimeout() method will hide the image after the specified time duration. This function will execute only once in its lifetime. But if you want repeated executions, then you can use the setInterval() instead of the setTimeout() method.

setInterval() Method

This method is used to trigger any task at some specific time continuously. Unlike the setTimeout() function, this function executes constantly.

Syntax

setInterval( function, milliseconds) ;

Example

Let us see an example to understand this method in a better way.

<!DOCTYPE html>
<html>
	<head>
		<!-- Including jQuery -->
		<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
		<center>
			<!-- Heading -->
			<h2>SetInterval() method</h2>
		</center>
		<script>
			$(document).ready(function() {
				$("#button").click(function() {
					setInterval("alert('Hello Ninjas');", 3000);
				});
			});
		</script>
	</head>

	<body>
		<center>
			<!-- Creating a button -->
			<button id="button">Click</button>
		</center>
	</body>
</html>


Output

SetInterval method

Explanation

In the above example, we created a button that, when clicked, will display the alert message ‘Hello Ninjas’. This message will be executed continuously every 3000 milliseconds/3 seconds till we refresh the page. The resultant output, whenever we click the button, will be:
 

SetInterval output

clearTimeout() Method

The clearTimeout() method is used to cancel the timer which the setTimeout() method sets.

Syntax

clearTimeout(timeoutID)


Here, the timeoutID is the ID the setTimeout() method returns.
Now let us look at an example to understand how to use this method.

Example

<!DOCTYPE html>
<html>
    <body>
        <div>
        
            <!-- Creating display button -->
            <button onclick="Display()">Display</button>
            <!-- Creating Stop button -->
            <button onclick="StopFunction()">Stop</button>
        </div>
        
        <script type="text/javascript">
            // Creating a variable to store the timer ID
            var timer;

            function Display() {
                // Calling setInterval method after every four seconds
                timer = setInterval(function(){ alert("Hello"); }, 4000);
            }

            function StopFunction() {
                // Terminating timer
                clearTimeout(timer);
            }
        </script>

    </body>
</html>


Output

clearTimeout() output

Explanation

In the above example, we can see that the setinterval() method will execute the alert message every 2 seconds till we call the clearTimeout() interval and pass the timer ID to it.

Frequently Asked Questions

What is the use of setTimeout in jQuery?

The setTimeout() in jQuery lets you pause for a moment, like setting a timer, before doing something on a website. It is useful in creating pauses or timed effects in web design.

How does setTimeout () work?

In jQuery, setTimeout() schedules a specified function or code block to run after a given time delay, measured in milliseconds. It operates asynchronously, which makes it useful for delayed actions or animations in jQuery-based web development.

What does the setTimeout () return?

This function returns the id of the timer whenever the ‘function’ begins executing. We can use this timer id to stop the execution with the help of the clearTimeout() function by passing the id as a parameter.

How to call a function with timeout in jQuery?

In jQuery, you use setTimeout() to call a function with a specified delay. The syntax is- setTimeout(function() { // code //}, delayInMilliseconds); Here, replace the "// code //" with your function code and the "delayInMilliseconds" with your required delay.

Conclusion

This article discusses how to use jQuery setTimeout() and setInterval, along with examples. We also discussed a method to stop the setTimeout() method. We hope this blog has helped you enhance your knowledge of setTimeout() in jQuery. If you want to learn more, then check out our articles.

And many more on our platform Coding Ninjas Studio.

Happy Learning!

Guided path
Free
gridgp-icon
Basics of javascript
10 chapters
68+ Problems
gp-badge
Earn badges and level up
Live masterclass