JavaScript has no sleep function, but we can easily solve it this way!

In order to make your browser sleep, just write this line of code:

await new Promise(_ => setTimeout(_, 2000));

This will make the browser sleep for 2 seconds (2000ms).

Please note that it works in modern browsers only (> 2017)! See browser compatibility for await on caniuse.com.

Let's create a reusable sleep function

const sleep = (ms = 2000) => new Promise(_ => setTimeout(_, ms));

Or with a more old days' notation:

function sleep(ms = 2000) { 
  return new Promise(function(_) {
    return setTimeout(_, ms)
  });
}

If you want to explore other features of Promise you can browse the MDN Doc.

How to use it

console.log(`Let's wait for 5s`);

await sleep(5000); // 5000ms = 5seconds

console.log(`5s have passed`);

Result in console:

> Let's wait for 5s
[waiting for 5 seconds]
> 5s have passed

Top-level await issue

Using top-level await might not work in some old browser/node versions. To solve this problem we can wrap our code with an immediately-invoked async function.

(async function() {

  console.log(`Let's wait for 5s`);

  await sleep(5000);

  console.log(`5s have passed`);

}());

Sleep function in old browsers

Just a note about Sleep function in old browser: it has usually been written this way, but it's definitely not "performance friendly".

function sleep(mss) {
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while(
    currentDate - date < milliseconds);
}

Demo

I created a stackblitz project with a simple example.