JavaScript: Wait 1 Second [Easy Guide]

Alvaro Trigo Avatar

Follow on Twitter

There are a few ways to tell JavaScript to wait for 1 second. Some are better than others, and some should only be used in specific circumstances.

Allow me to explain myself.

How to Wait 1 Second in JavaScript?

To wait 1 second in JavaScript, use the setTimeout function with 1000ms, which is the equivalent of 1 sec. If you want a better solution, use the Promise JS function or create a do... while loop.

Here are three different solutions to sleep 1 second in JavaScript:

Wait using setTimeout

One of the easiest ways to achieve a 1 second delay is by using the setTimeout function that lives in the window global object.

Here’s an example:

console.log("Executed now");

// 1 second delay
setTimeout(function(){
    console.log("Executed after 1 second");
}, 1000);
Code language: JavaScript (javascript)

The setTimeout function takes two parameters. One is the callback function that will get executed after a specific time, and the other is the number of milliseconds we want to delay the execution. In this case, we are using 1000ms, which is the equivalent of 1 second.

Now, this looks great and simple! However, here’s the trick:

console.log("Executed now");

// 1 second delay
setTimeout(function(){
    console.log("Executed after 1 second");
}, 1000);

// Notice this!
console.log("Executed before the delay, but after the 1st console.log");
Code language: JavaScript (javascript)

Notice how our setTimeout function runs asynchronously and that it won’t stop the flow of our program. This means that anything defined after it in the code will run before the delay.

This will probably be okay in any circumstance, and the solution to it can be as simple as placing the rest of the code inside the timeout, but it is not something that can serve us in every scenario.

Also, if you want to keep on adding delays inside the same delayed function, we can quickly run into what is known as the callback hell (and that’s not pretty).

Therefore, keep on reading!

Wait using Promise

Another way to make an asynchronous wait with modern JavaScript is by using the Promise function.

Note that Promises are part of the ES6 standard and won’t work in some legacy browsers such as IE 11. Check out the compatiblity table.

If we combine the setTimeout function with promises, we can create a more readable code and place our whole code inside the same (async) function.

The main advantage, compared to the setTimeout method we explained before, is that we can reuse the delay function. Making our code much more clean and straightforward.

function delay(milliseconds){
    return new Promise(resolve => {
        setTimeout(resolve, milliseconds);
    });
}

async function init(){
    console.log("Executed now");

    await delay(1000);

    console.log("Executed after 1 second wait");

    await delay(1000);

    console.log("Executed after 2 seconds wait");
}

init();

console.log("Executed after the 1st log and before the 2 delays");
Code language: JavaScript (javascript)

You can test it here:

CodePen Embed Fallback

Wait using a loop

This is the only way to completely break the user flow and force JavaScript to pause synchronously.

It’s not the perfect solution, and I would argue is probably undesirable. JavaScript is an asynchronous language, and we should take advantage of it instead of using hacky solutions to make our code synchronous.

Nevertheless, here’s how to do it:

var wait = (ms) => {
    const start = Date.now();
    let now = start;
    while (now - start < ms) {
      now = Date.now();
    }
}

console.log("Executed now");
wait(1000);
console.log("Executed after 1 second");
Code language: JavaScript (javascript)

We basically check the current time with the Date function, and we create a do ... while loop that will only exit if more than 1000 milliseconds have passed since we started the loop.

See the problem here? We are basically keeping our computer/browser busy by running a “nonsense” loop and comparing dates just to get our delay.

If we wait longer than 1 second, chances are that our browser crashes or that our page stops responding as usual. Even if we use a 1-second value, things might not always work as we expect. The DOM render happens after the JavaScript functions stack has cleared and the browser can accept new events.

And to prove it, see the following example, where the console.log gets fired after 1 second (as we would expect), but both of the DOM writes happen at the same time:

CodePen Embed Fallback

If possible, avoid this solution in favor of the previous ones.

Conclusion

From the 3 ways of making JavaScript wait 1 second (or any other lapse of time), you should be fine by using any of the first two.

I’ve used setTimeout multiple times, and it works perfectly on most occasions.

However, the modern way of pausing the execution with promises can give you more flexibility and create more maintainable code in the long run.

Was this page helpful?