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

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

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


当前回答

需要使用“休眠”方法的对象的方法,如下所示:

function SomeObject() {
    this.SomeProperty = "xxx";
    return this;
}
SomeObject.prototype.SomeMethod = function () {
    this.DoSomething1(arg1);
    sleep(500);
    this.DoSomething2(arg1);
}

几乎可以翻译为:

function SomeObject() {
    this.SomeProperty = "xxx";
    return this;
}
SomeObject.prototype.SomeMethod = function (arg1) {
    var self = this;
    self.DoSomething1(arg1);
    setTimeout(function () {
        self.DoSomething2(arg1);
    }, 500);
}

不同之处在于,“SomeMethod”操作在执行操作“DoSomething2”之前返回。“SomeMethod”的调用者不能依赖于此。由于“睡眠”方法不存在,我使用后一种方法并相应地设计代码。

其他回答

在sleep方法中,可以返回任何可执行的对象。不一定是新的承诺。

例子:

constsleep=(t)=>({then:(r)=>setTimeout(r,t)})常量someMethod=async()=>{console.log(“hi”);等待睡眠(5000)console.log(“再见”);}someMethod()

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;}

在LiveScript(编译为JavaScript)中,可以执行以下操作:

sleep = (ms, func) -> set-timeout func, ms

console.log "hello-1"
<- sleep 2000ms
console.log "hello-2"
<- sleep 2000ms
console.log "hello-3"

现在还可以使用本机模块util来提供常规同步函数。

const { promisify } = require('util')
const sleep = promisify(setTimeout)

module.exports = () => {
  await someAsyncFunction()
  await sleep(2000)
  console.log('2 seconds later...')
}

这可能会奏效。它在C和JavaScript中对我有用。

function sleep(time) {
  var x = 0;
  for(x = 0;x < time;x++) {/* Do nothing */}
}