Devtrium

How to sleep in JavaScript?

July 23, 20211 min read

Introduction

It's quite rare, but I've regularly found myself in situations where I wanted my code to wait for a set amount of time before continuing. It often came up in testing asynchronous functions for example.

But how to sleep in JavaScript? The solution turns out to be simple using Promises and a timeout, but not necessarily obvious. Here it is!

How to sleep 😴

Here's a sleep function:

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

This function returns a Promise that resolves in a set amount of milliseconds. The usage is quite simple.

// wait 1 second
await sleep(1000);

// do what you want

Of course as it's using await you should use it inside an async function. Otherwise you can use .then:

sleep(1000).then(() => {
  // do what you want
});

Did you enjoy this article?

If so, a quick share on Twitter could really help out!