What is the JavaScript version of sleep()?

fmsf picture fmsf · Jun 4, 2009 · Viewed 2.9M times · Source

Is there a better way to engineer a sleep in JavaScript than the following pausecomp function (taken from here)?

function pausecomp(millis)
{
    var date = new Date();
    var curDate = null;
    do { curDate = new Date(); }
    while(curDate-date < millis);
}

This is not a duplicate of Sleep in JavaScript - delay between actions; I want a real sleep in the middle of a function, and not a delay before a piece of code executes.

Answer

Dan Dascalescu picture Dan Dascalescu · Oct 7, 2016

2017 — 2019 update

Since 2009 when this question was asked, JavaScript has evolved significantly. All other answers are now obsolete or overly complicated. Here is the current best practice:

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

async function demo() {
  console.log('Taking a break...');
  await sleep(2000);
  console.log('Two seconds later, showing sleep in a loop...');

  // Sleep in loop
  for (let i = 0; i < 5; i++) {
    if (i === 3)
      await sleep(2000);
    console.log(i);
  }
}

demo();

This is it. await sleep(<duration>).

Or as a one-liner:

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

Note that,

  1. await can only be executed in functions prefixed with the async keyword, or at the top level of your script in some environments (e.g. the Chrome DevTools console, or Runkit).
  2. await only pauses the current async function

Two new JavaScript features helped write this "sleep" function:

Compatibility

If for some weird reason you're using Node older than 7 (which has reached end of life), or are targeting old browsers, async/await can still be used via Babel (a tool that will transpile JavaScript + new features into plain old JavaScript), with the transform-async-to-generator plugin.