什么是sleep()的JavaScript版本? [英] What is the JavaScript version of sleep()?

查看:184
本文介绍了什么是sleep()的JavaScript版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有更好的方法在JavaScript中设计 sleep 而不是以下 pausecomp 函数(从这里取得)?

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

这不是在JavaScript中睡眠 - 在操作之间延迟;我希望在函数中间有一个真正的睡眠,而不是在一段代码执行之前的延迟。

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年更新



自2009年提出这个问题以来,JavaScript已经发生了重大变化。所有其他答案现在已经过时或过于复杂。以下是当前的最佳做法:

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

您可以直接试用此代码在Runkit上。请注意,

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


  1. await 只能在以前缀<$的函数中执行c $ c> async 关键字。 Runkit在执行之前将代码包装在异步函数中。

  2. await 仅暂停当前的 async function

  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

两个新的JavaScript功能帮助编写了这个实际的睡眠功能:

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.

    在节点v0.12 + 承诺。 com /#feat = promisesrel =noreferrer>在浏览器中广泛支持,IE除外
  • async / await 登陆V8并且默认启用,因为Chrome 55

    • 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
      • and also landed in Firefox Nightly in November 2016

      如果出于某种原因,您使用的是7岁以上的Node,或者定位的是旧浏览器, async / 等待仍然可以通过 Babel (一个 transpile JavaScript +新功能到普通的旧JavaScript), transform-async-to-generator 插件。运行

      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
      

      使用以下内容创建 .babelrc

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

      然后用

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

      但同样,你不需要这个如果您使用的是Node 7或更高版本,或者您的目标是现代浏览器。

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

      这篇关于什么是sleep()的JavaScript版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆