What's the JavaScript version of sleep

There’s no sleep function in JavaScript, how can we make one?

Let’s jump right in and write the function.

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

It’s a basic function that when called returns a Promise that’s resolved after the given number of milliseconds.

How do we use this function?

// sleep for 1 second
sleep(1000).then(() => {
    // do this after 1 second
});
// do this first

Please note that any code placed after sleep will run before the code inside the then function.

We can also use async/await

// sleep for 1 second
await sleep(1000);

// do this after 1 second

That’s it. A super quick way to create a sleep function in JavaScript.

Useful for when we, for example, want to sleep an authentication process a random number of milliseconds to obfuscate if our server is busy or not.

I share web dev tips on Twitter, if you found this interesting and want to learn more, follow me there

Or join my newsletter

More articles More articles