What is the JavaScript version of sleep()?

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.


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(<duration>) .

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

  • await can only be executed in functions prefixed with the async keyword. Runkit wraps your code in an async function before executing it.
  • await only pauses the current async function
  • Two new JavaScript features helped write this actual "sleep" function:

  • Promises, a native feature of ES2015 (aka ES6). We also use arrow functions in the definition of the sleep function.
  • The upcoming async/await feature lets the code explicitly wait for a promise to settle.
  • Compatibility

  • promises are supported in Node v0.12+ and widely supported in browsers, except IE
  • async / await landed in V8 and has been enabled by default since Chrome 55
  • it landed in Node 7 in October 2016
  • has also landed in Firefox nightly in Nov 2016-Nov
  • 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.


    (See the updated answer for 2016)

    I think it's perfectly reasonable to want to perform an action, wait, then perform another action. If you are used to writing in multi-threaded languages, you probably have the idea of yielding execution for a set amount of time until your thread wakes up.

    The issue here is that JavaScript is a single-thread event-based model. While in a specific case, it might be nice to have the whole engine wait for a few seconds, in general it is bad practice. Suppose I wanted to make use of your functions while writing my own? When I called your method, my methods would all freeze up. If JavaScript could somehow preserve your function's execution context, store it somewhere, then bring it back and continue later, then sleep could happen, but that would basically be threading.

    So you are pretty much stuck with what others have suggested -- you'll need to break your code up into multiple functions.

    Your question is a bit of a false choice, then. There is no way to sleep in the way you want, nor should you pursue the solution you suggest.


    In JavaScript, I rewrite every function so that it can end as soon as possible. You want the browser back in control so it can make your DOM changes.

    Every time I've wanted a sleep in the middle of my function, I refactored to use a setTimeout() .

    I am going to edit this answer because i found this as useful:

    The infamous sleep, or delay, function within any language is much debated. Some will say that there should always be a signal or callback to fire a given functionality, others will argue that sometimes an arbitrary moment of delay is useful. I say that to each their own and one rule can never dictate anything in this industry.

    Writing a sleep function is simple and made even more usable with JavaScript Promises:

    // sleep time expects milliseconds
    function sleep (time) {
      return new Promise((resolve) => setTimeout(resolve, time));
    }
    
    // Usage!
    sleep(500).then(() => {
        // Do something after the sleep!
    });
    
    链接地址: http://www.djcxy.com/p/16400.html

    上一篇: 僵尸是否存在......在.NET中?

    下一篇: 什么是sleep()的JavaScript版本?