jQuery setTimeout: 6 Demos including JavaScript

Learn how to schedule code to run after a specified delay in JavaScript using setTimeout.

Purpose of setTimeout function

The setTimeout() function of JavaScript is used to delay certain actions or execution of the code placed directly inside that function or at another JS function.

The delay or time is specified in milliseconds in setTimeout function.

Not only this function is used in native JavaScript but you may use setTimeout in jQuery as well. I will show you how later in this tutorial, so keep reading.

Note: The second “T” is capital in the setTimeout function. All other letters are small.

Using setTimeOut function in jQuery

You may use the setTimeout function in the jQuery code to delay an action.

First, let me show a simple example of using setTimeout where I will display an alert by an interval of 3000 milliseconds.

See online demo and code

The following jQuery code is used:

$(document).ready(function(){

setTimeout(function(){

alert("Using setTimeout in jQuery");}, 2000);

});

An example of using setTimeout with AJAX post method

  • In this example, the data is loaded in a div element by using the AJAX $.post method.
  • The code is placed inside the document.ready function, so as the demo page loads, the data will be loaded from the text file into the div element.
  • However, the code of $.post method is written inside the setTimeout method which will delay displaying the text by two seconds.

JavaScript setTimeout ajax

Following is the complete code for this example: (make sure to place the text file correctly)

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.1.min.js"></script>
<style>
.divclass {
  background: #038D98;
  height: auto;
  width:300px;
  border-radius: 15px;
  padding:20px;
  font-size:16px;
  color:#fff;  
}
</style>
</head>

<body>
<div class="divclass"><p><strong>A demo of setTimeout with jQuery $.post</strong></p> 


<script type="text/javascript">
$(document).ready(function(){
    setTimeout(function(){
    $.post("posttst.txt",function(postresult){
        $(".divclass").append(postresult);
        });}, 2000);        
});


</script>
</body>
</html>

A demo of jQuery setTimeout with show/hide method

In this example, a div element is displayed as the web page loads.

After 3 seconds, the div will disappear by using the hide method of jQuery. The $.hide method is placed inside the setTimeout function.

The $.show and $.hide methods have their own duration parameter, however, this will be in action after the setTimeout interval is finished and the $.hide method starts executing.

See the demo and code online:

JavaScript setTimeout hide

See online demo and code

Notice this code in the <script> section:

    setTimeout(function(){

$(".divclass").hide("2000")

}, 3000);

In the $.hide method, I used 2000 milliseconds while setTimeout jQuery function is given the 3000 milliseconds duration.So, the code for hiding the div will start executing after three seconds, and the hide method will hide the div in two seconds.

I have placed this code in the document.ready function.

You can use this at the click event of a button or link or associate with some other element as well.

Syntax to use setTimeout function in JavaScript

You have to specify two parameters in the setTimeout function.

This is how you can use the setTimeout JavaScript function:

window.setTimeout(‘Function_to_execute()', 5000);

Or you can use this:

setTimeout(‘Function_to_execute()', 5000);

The first parameter is a JS function while other is the time in milliseconds. Rather than using the function, you can use the code directly.

Although, there is no difference as far execution is concerned in the above syntax, the window.setTimeout specifies the global object window.

An example of displaying text in a div with three second interval

In this demo, a div is created to demonstrate the setTimeout function.

As you click the button, “Execute setTimeout function”, a JS function is called where the setTimeout function is used.

Inside that setTimeout function, another function is called at an interval of 3000 milliseconds that will display the text in an HTML span tag inside that div element.

See the demo online:

JavaScript setTimeout

See online demo and code

The following code is used in the <script> section:

<script type="text/javascript">

function timeoutdemo(){

window.setTimeout('disptxt()', 3000);

}


function disptxt(){

document.getElementById("setTimeoutdemo").innerHTML = "This is setTimeout demo with three seconds interval!";

}


</script>

An example to redirect to another web page with 2 second gap

The setTimeout function can be used to redirect to another website with the specified interval as per the user’s action or automatically.

For example, if the page is idle or you want to redirect after a user’s action, you may do this by setTimeout function as shown below.

JavaScript setTimeout redirect

See online demo and code

As you click the button “Redirect me to Home page”, it will display an alert and as you press the OK button, the browser will be redirected to the home page in two seconds.

This code is used:

<script type="text/javascript">

function timeoutdemo(){

alert ("You will be redirected in two seconds!");

window.setTimeout('redirectMe()', 2000);

}



function redirectMe(){

window.location = "https://www.jquery-az.com/";

}



</script>

A demo to display a pop-up automatically after the web page is loaded

In this example, I am using a third-party alert plug-in to display a pop-up with a subscription form after five seconds.

Simply click the demo link and wait for five seconds to display the alert:

JavaScript setTimeout subscribe

See online demo and code

For the demo, I have used the SweetAlert plug-in, which enables the creation of nice JavaScript alerts.

After creating the code for the alert, I simply used the setTimeout JavaScript function where I called the function containing SweetAlert code:

<script type="text/javascript">

window.setTimeout('JSalert()', 5000);



function JSalert(){

swal({   title: "Subscribe for updates!",

text: "Enter your email address:",

type: "input",

showCancelButton: true,

closeOnConfirm: false,

animation: "slide-from-top",

inputPlaceholder: "Your Email address" },



function(inputValue){

if (inputValue === false)

return false;

if (inputValue === "") {

swal.showInputError("Please enter email!");

return false

}

swal("Action Saved!", "You entered following email: " + inputValue, "success"); });

}



</script>

You may read more about this add-on here, to learn and use in your web projects.

Similarly, you may display a warning, information, confirm, and some other popup by using the setTimeout function.
Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we unravel the mysteries of coding together!