In jQuery, we can wait 1 second before executing a function or some code with the use of the setTimeout method.

setTimeout(function(){
  //Code that will run after 1000 milliseconds
}, 1000);

You can see in the code above that the setTimeout() method has the second parameter value of 1000. This is how long (in milliseconds) the method will wait until running the function in the first parameter. In this case, it is 1000 milliseconds or 1 second.


Let’s say we want to run code that executes an alert box after 1 second. We can do this easily using the setTimeout method.

Here is the JavaScript code that can make this happen.

setTimeout(function(){
  alert("1 second has passed.")
}, 1000);

Let’s take a look at this example below.

Using jQuery to Wait 1 to Show an Alert Box

In this example, we will use the setTimeout() method to show an alert box after 1 second has passed that will display a message when finished. It will start when the user presses a button.

Here is the simple HTML setup:

Start

To make this countdown timer happen, we will use the setTimeout() method. We will use jQuery to wait 1 second using the setTimeout() method.

In our setTimeout() method, once the 1 second is up, we will have an alert box alert the user that 1 second has passed.

Here is the JavaScript code:

function startTimer(){
  setTimeout(function(){
    //Send alert message to the user
    alert("1 second has passed.");
  }, 1000);
};

The final code and output for this example of how to wait 1 second before displaying an alert box is below:

Code Output:

Start

Full Code:

Start

Hopefully this article has been useful for you to understand how to use jQuery to wait 1 second.

Categorized in:

jQuery,

Last Update: March 11, 2024