How to Wait 1 Second in JavaScript

Introduction

In JavaScript, waiting a specific amount of time before executing a function or piece of code is a common requirement. This can be useful for creating delays, like for periodically making an AJAX request, running animations, or even simply allowing a certain process to complete before moving on.

One of the ways to accomplish this is by using the setTimeout function, which allows you to specify a delay, in milliseconds, before executing a given callback function. In this tutorial, we'll learn how to use setTimeout to wait for one second in JavaScript. But of course, this can be generalized to wait any amount of time as well.

Delaying 1 Second

To use setTimeout to wait for one second in JavaScript, you would pass two arguments to the function: a callback and an integer delay, in milliseconds. The callback function is the code that you want to execute after the specified delay. For example:

setTimeout(() => {
    console.log('Hello, World!');
}, 1000);

In this code, the callback function simply logs "Hello, World!" to the console. The delay is specified as 1000 milliseconds, or 1 second.

Here is an example of using setTimeout to delay an alert message:

setTimeout(() => {
    alert('This alert appeared after 1 second!');
}, 1000);
Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

These examples show the callback being passed directly to the setTimeout function. However, you can also use setTimeout to delay the execution of a function that has been defined previously in your code. For example:

function sayHello() {
    console.log('Hello, World!');
}

setTimeout(sayHello, 1000);

One common use case for setTimeout is to create a delay before showing or hiding an element on a page. For example, you could show a transition animation for 1 second before displaying the results of an AJAX request. Here is an example of using setTimeout to hide a div element after 1 second:

setTimeout(function() {
    document.getElementById('myDiv').style.display = "none";
}, 1000);

Another common use-case is to use setTimeout to create a simple countdown timer. For example, the following code will log the numbers from 10 down to 1 to the console, with a 1 second delay between each:

for (let i = 10; i > 0; i--) {
    setTimeout(function() {
        console.log(i);
    }, (10 - i) * 1000);
}

Conclusion

setTimeout is a useful function for creating delays and scheduling tasks in JavaScript. By passing a callback function and a delay, in milliseconds, to setTimeout, you can execute code after the specified amount of time has passed.

Last Updated: April 18th, 2023
Was this helpful?

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms