DEV Community

Cover image for JavaScript has no sleep function, but we can easily solve it this way!
Daniel Zotti
Daniel Zotti

Posted on • Originally published at danielzotti.it

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));
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

Or with a more old days' notation:

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

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`);
Enter fullscreen mode Exit fullscreen mode

Result in console:

> Let's wait for 5s
[waiting for 5 seconds]
> 5s have passed 
Enter fullscreen mode Exit fullscreen mode

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`);

}());  
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

Demo

I created a stackblitz project with a simple example.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs