什么是sleep()的JavaScript版本? [英] What is the JavaScript version of sleep()?
问题描述
是否有更好的方法在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,
-
await
只能在以前缀<$的函数中执行c $ c> async 关键字。 Runkit在执行之前将代码包装在异步函数中。 -
await
仅暂停当前的async
function
await
can only be executed in functions prefixed with theasync
keyword. Runkit wraps your code in an async function before executing it.await
only pauses the currentasync
function
两个新的JavaScript功能帮助编写了这个实际的睡眠功能:
Two new JavaScript features helped write this actual "sleep" function:
- 承诺,ES2015的原生特色(又名ES6)。我们还在定义中使用箭头功能睡眠功能。
- 即将推出
async / await
功能让代码明确等待承诺解决。
- 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.
-
async
/await
登陆V8并且默认启用,因为Chrome 55
- 它在Node中登陆 2016年10月7日
- 并登陆 2016年11月的Firefox每晚
- 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 thetransform-async-to-generator
plugin. Runnpm 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屋!
在节点v0.12 + 和承诺。 com /#feat = promisesrel =noreferrer>在浏览器中广泛支持,IE除外