What is the JavaScript version of sleep()?

Spread the love

Question Description

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.

Practice As Follows

2017 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 second later');
}

demo();

This is it. await sleep().

You can try this code live on Runkit. Note that,

  1. await can only be executed in functions prefixed with the async keyword. Runkit wraps your code in an async function before executing it.
  2. await only pauses the current async function

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

Compatibility

If for some reason you're using Node older than 7, 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. Run

npm install babel-cli --save

Create .babelrc with:

{
  "plugins": [
    "transform-async-to-generator",
  ]
}

Then run your code with

node_modules/babel-cli/bin/babel-node.js sleep.js

But again, you don't need this if you're using Node 7 or later, or if you're targeting modern browsers.

Leave a Comment