有没有比下面的pausecomp函数(取自此处)更好的方法来设计JavaScript中的睡眠?

function pausecomp(millis)
{
    var date = new Date();
    var curDate = null;
    do { curDate = new Date(); }
    while(curDate-date < millis);
}

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


当前回答

这里大多数解决方案的问题是它们倒带堆栈。在某些情况下,这可能是一个大问题。在这个例子中,我展示了如何以不同的方式使用迭代器来模拟真实的睡眠。

在本例中,生成器正在调用自己的next(),因此一旦它启动,它就自己运行了。

var h = a();
h.next().value.r = h; // That's how you run it. It is the best I came up with

// Sleep without breaking the stack!!!
function *a(){
    var obj = {};

    console.log("going to sleep....2s")

    setTimeout(function(){obj.r.next();}, 2000)
    yield obj;

    console.log("woke up");
    console.log("going to sleep no 2....2s")
    setTimeout(function(){obj.r.next();}, 2000)
    yield obj;

    console.log("woke up");
    console.log("going to sleep no 3....2s")

    setTimeout(function(){obj.r.next();}, 2000)
    yield obj;

    console.log("done");
}

其他回答

干得好。正如代码所说,不要做一个糟糕的开发人员,在网站上使用它。这是一个开发实用函数。

// Basic sleep function based on ms.
// DO NOT USE ON PUBLIC FACING WEBSITES.
function sleep(ms) {
    var unixtime_ms = new Date().getTime();
    while(new Date().getTime() < unixtime_ms + ms) {}
}

让事情看起来像大多数人想要的更好的解决方案是使用匿名函数:

alert('start');
var a = 'foo';
// Lots of code
setTimeout(function(){  // Beginning of code that should run AFTER the timeout
    alert(a);
    // Lots more code
}, 5000);  // Put the timeout here

这可能是最接近你想要的东西。

注意,如果你需要多次睡眠,这可能会在匆忙中变得很难看,你可能需要重新考虑你的设计。

sleep()的JavaScript版本是什么?

这已经在当前接受的答案中得到了回答:

await new Promise(r => setTimeout(r, 1000));

两个异步函数同时运行

最好将它放在函数sleep()中,然后等待睡眠()。要使用它,需要一些上下文:

函数sleep(ms){return new Promise(r=>setTimeout(r,ms));}(异步函数slowDemo(){console.log(“启动慢演示…”);等待睡眠(2000);console.log('lowDemo:两秒后…');})();(异步函数fastDemo(){console.log('开始快速演示…');等待睡眠(500);for(设i=1;i<6;i++){console.log('上次演示:'+(i*0.5)+'秒后…');等待睡眠(500);}})();.作为控制台包装{最大高度:100%!重要;顶部:0;}

两个异步调用依次运行–一个接一个

但假设slowDemo产生的结果是fastDemo取决于。在这种情况下,在fastDemo开始之前,slowDemo必须运行到完成:

函数sleep(ms){return new Promise(r=>setTimeout(r,ms));}(异步()=>{await(异步函数slowDemo(){console.log(“启动慢演示…”);等待睡眠(2000);console.log('slowDemo:两秒后…完成!');})();(异步函数fastDemo(){console.log('开始快速演示…');等待睡眠(500);设i=-2;对于(i=1;i<5;i++){console.log('上次演示:'+(i*0.5)+'秒后…');等待睡眠(500);}console.log('fastDemo:'+(i*0.5)+'秒后。已完成!');})();})();.作为控制台包装{最大高度:100%!重要;顶部:0;}

如果您想要在所有浏览器上都可用的代码,请使用setTimeout()和clearTimeout(()。如果您深入阅读答案,您可能会注意到,接受的答案打破了Internet Explorer 11中所有JavaScript编译,使用此解决方案后,大约有5%的用户仍在使用此积极开发的浏览器并需要支持。

这几乎打破了一切。已知有报道称箭头函数破坏了Drupal、WordPress、Amazon AWS、IBM等软件的Internet Explorer 11功能,甚至在Stack Overflow上也有专门的讨论。

看看吧。。。

使用setTimeout()和clearTimeout(。。。

工作JSBin演示

var超时;功能休眠(延迟){if(超时){clearTimeout(超时);}timeout=setTimeout(函数){myFunction();},延迟);}console.log(“休眠1秒”);睡眠(1000);函数myFunction(){console.log(“睡眠了1秒钟!”);}

使用更好的DX实现更安全的异步睡眠

我使用睡眠进行调试。。。我忘了用wait太多次了。让我挠头。我在写下面的实时片段时忘记使用await。。。不再!

如果您在1毫秒内运行了两次,下面的睡眠功能会提醒您。如果您确定使用了await,它还支持传递一个相当的参数。它不会投掷,因此可以安全地用作睡眠的替代品。享受

是的,实时片段中有一个JavaScript版本。

// Sleep, with protection against accidentally forgetting to use await
export const sleep = (s: number, quiet?: boolean) => {
  const sleepId = 'SLEEP_' + Date.now()
  const G = globalThis as any
  if (G[sleepId] === true && !quiet) {
    console.error('Did you call sleep without await? use quiet to hide msg.')
  } else {
    G[sleepId] = true
  }
  return new Promise((resolve) => {
    !quiet && setTimeout(() => {
      delete G[sleepId]
    }, 1)
    setTimeout(resolve, (s * 1000) | 0)
  })
}

//睡眠,防止意外忘记使用等待常量睡眠=(s,安静)=>{constsleepId='SLEEP_'+Date.now()const G=全局此if(G[sleepId]==true&&!quiet){console.error('您是否在没有等待的情况下调用sleep?使用quiet隐藏消息。')}其他{G[sleepId]=真}return new Promise((resolve)=>{!quiet&&setTimeout(()=>{删除G[sleepId]}, 1)setTimeout(解析,(s*1000)|0)})}常量main=async()=>{console.log('休眠1秒…')等待睡眠(1)console.log('使用等待的目标…')睡眠(99)睡眠(99)等待睡眠(1,true)console.log(“开发人员快乐!”)}main()

与公认更容易阅读的相比:

const sleep = (s: number) =>
  new Promise((p) => setTimeout(p, (s * 1000) | 0))