Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

javascript - sleep()的JavaScript版本是什么?(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 )?

(是否有比下面的pausecomp函数( 从此处获取 )更好的方法来设计JavaScript的sleep ?)

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 ;

(这不是JavaScriptSleep的重复-动作之间的延迟 ;)

I want a real sleep in the middle of a function, and not a delay before a piece of code executes.

(我希望在函数中间真正入睡 ,而不是在执行一段代码之前没有延迟。)

  ask by community wiki translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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,

(注意,)

  1. 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 。)

  2. 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插件。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...