有没有比下面的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");
}

其他回答

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

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

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

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

setTimeout是JavaScript异步方法的一部分(开始执行的方法,其结果将在将来某个时候返回到一个名为回调队列的组件,稍后将执行)

您可能想做的是将setTimeout函数包装在Promise中。

承诺示例:

constsleep=time=>newPromise(res=>setTimeout(res,time,“已完成睡眠”));//使用本机承诺sleep(2000).then(msg=>console.log(msg));

异步/等待示例:

constsleep=time=>newPromise(res=>setTimeout(res,time,“已完成睡眠”));//在顶层使用异步/等待(异步函数(){const msg=等待睡眠(2000);console.log(消息);})();

阅读有关setTimeout的更多信息

这会帮你的。

var reloadAfter = 10; //seconds
var intervalId = setTimeout(function() {
    //code you want to execute after the time waiting
}, reloadAfter * 1000); // 60000 = 60 sec = 1 min

你可以这样做。所有函数都可以继承的休眠方法:

Function.prototype.sleep=函数(延迟,…args){setTimeout(()=>this(…args),delay)}console.log.sleep(2000年,“你好,世界!!”)

我建议以前的python开发人员使用此方法

const sleep = (time) => {
   return new Promise((resolve) => setTimeout(resolve, Math.ceil(time * 1000)));
};

用法:

await sleep(10) // for 10 seconds