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

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

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


当前回答

2021+更新

如果您正在寻找以下替代方案:

let sleep = ms => new Promise(res=>setTimeout(res,ms));

然后使用这个:

let sleep = async ms => void await Atomics.waitAsync(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms).value;

请注意,在发布此问题时,它是第3阶段提案。此外,它可能要求您的站点进行跨源隔离。要查看它在浏览器中是否有效,(在堆栈溢出上)请尝试以下操作:

let sleep=async ms=>void await Atomics.waitAsync(新Int32Array(新SharedArray Buffer(4)),0,0,ms).value;void异步函数(){console.log(1);等待睡眠(2000);console.log(2);}()

其他回答

为了测试,我需要一段忙碌的等待。我不想拆分代码,因为这需要很多工作,所以一个简单的for为我做了这件事。

for (var i=0; i<1000000; i++){                  
    // Waiting
}

我看不出这样做有什么坏处,这对我来说很有好处。

如果您想要在所有浏览器上都可用的代码,请使用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秒钟!”);}

如果确实要暂停脚本,可以执行以下操作:

var milliseconds;
var pretime;
var stage;

function step(time){
  switch(stage){
    case 0:
      //Code before the pause

      pretime=time;
      milliseconds=XXX;
      stage=1;
      break;
    case 1:
      //Code that is looped through while paused

      if(time-pretime >= milliseconds){
        //Code after the pause

        pretime=time;
        milliseconds=XXX;
        stage=2;
      }
      break;
    case 2:
      //Code that is looped through while paused

      if(time-pretime >= milliseconds){
        //Code after the pause

        pretime=time;
        milliseconds=XXX;
        stage=3;
      }
      break;
    case 3:
      //Etc...
  }

  Window.requestAnimationFrame(step)
}

step();

如果您使用循环,这可能正是您想要的,并且您可以以某种方式对其进行更改,从而获得伪多线程,其中一些函数等待一段时间,其他函数正常运行。我一直在纯JavaScript游戏中使用这个。

第一:

定义要执行的函数,如下所示:

function alertWorld(){
  alert("Hello, World!");
}

然后使用setTimeout方法安排其执行:

setTimeout(alertWorld, 1000)

注意两件事

第二个参数是以毫秒为单位的时间作为第一个参数,必须只传递函数的名称(引用),而不传递括号

如果您真的需要等待那么多秒,那么当前接受的使用async/await和setTimeout的解决方案是完美的。然而,如果您将其用于屏幕动画,则应该真正使用requestAnimationFrame()。此函数的功能与setTimeout非常相似,但回调仅在用户可见动画时调用。这意味着,如果您在网站上运行动画,并且用户切换选项卡,动画将暂停并节省电池寿命。

这里是使用requestAnimationFrame的wait方法的实现。它接收多个帧,并在它们全部通过后解析:

常量动画等待=(帧)=>新承诺((决心)=>{让framesPassed=0;requestAnimationFrame(函数循环(){如果(++framesPassed>=帧)返回resolve();requestAnimationFrame(循环);});});//演示用打字机效果const content=document.querySelector(“.content”);异步函数类型Writer(endText,等待){content.textContent=“”;for(const letter of endText){content.textContent+=字母;wait animationWait(等待);}}typeWriter(“好的。这个简单的打字机效果是requestAnimationFrame的一个例子。”,8);<p>动画将在下面播放;尝试切换选项卡并查看动画暂停。</p><code class=“content”></code>

阅读有关requestAnimationFrame的更多信息

浏览器支持(IE10+)