旧行李 2009-06-04 14:41 采纳率: 25%
浏览 1141
已采纳

什么是 JavaScript 版本的睡眠?

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.

转载于:https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep

  • 写回答

30条回答

  • ℡Wang Yan 2016-10-07 09:44
    关注

    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 seconds later');
    }
    
    demo();

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

    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.

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(29条)

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据