2017 — 2019 update(2017年— 2019年更新)
Since 2009 when this question was asked, JavaScript has evolved significantly.
(自2009年提出这个问题以来,JavaScript取得了长足的发展。)
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, showing sleep in a loop...'); // Sleep in loop for (let i = 0; i < 5; i++) { if (i === 3) await sleep(2000); console.log(i); } } demo();
This is it.(就是这个。) await sleep(<duration>)
.(await sleep(<duration>)
。)
Note that,
(注意,)
-
await
can only be executed in functions prefixed with the async
keyword, or at the top level of your script in some environments (eg the Chrome DevTools console, or Runkit).(只有在以async
关键字为前缀的函数中或在某些环境中(例如,Chrome DevTools控制台或Runkit)在脚本的顶层执行await
。)
-
await
only pauses the current async
function(await
只会暂停当前的async
功能)
Two new JavaScript features helped write this "sleep" function:
(两个新的JavaScript功能帮助编写了此“睡眠”功能:)
Compatibility(兼容性)
If for some weird reason you're using Node older than 7 (which has reached end of life ), 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.
(如果您正在使用节点年纪比7(已经达成了一些奇怪的原因生命的尽头 ),或瞄准旧的浏览器, async
/ await
仍然可以通过使用巴别塔 (一种工具,将transpile的JavaScript +新特性的老式JavaScript),以及transform-async-to-generator
插件。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…