有没有比下面的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);}()
需要使用“休眠”方法的对象的方法,如下所示:
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”的调用者不能依赖于此。由于“睡眠”方法不存在,我使用后一种方法并相应地设计代码。
这里的大多数答案都是错误的,或者至少是过时的。没有理由JavaScript必须是单线程的,事实上也不是。今天,所有主流浏览器都支持工人。在此之前,Rhino和Node.js等其他JavaScript运行时支持多线程。
“JavaScript是单线程的”不是有效答案。例如,在工作线程中运行睡眠函数不会阻止UI线程中运行的任何代码。
在支持生成器和yield的较新运行时中,可以在单线程环境中为sleep函数带来类似的功能:
// This is based on the latest ES6 drafts.
// JavaScript 1.7+ (SpiderMonkey/Firefox 2+) syntax is slightly different
// Run code you want to sleep here (omit star if using JavaScript 1.7)
function* main(){
for (var i = 0; i < 10; i++) {
// To sleep for 10 milliseconds 10 times in a row
yield 10;
}
yield 5;
console.log('I just slept 5 milliseconds!');
}
// Resume the given generator after ms milliseconds
function resume(ms, generator){
setTimeout(function(){
// Omit .value if using JavaScript 1.7
var nextSleep = generator.next().value;
resume(nextSleep, generator);
}, ms);
}
// Initialize a generator and get first sleep for the recursive function
var
generator = main(),
firstSleep = generator.next().value;
// Initialize recursive resume function
resume(firstSleep, generator);
这种对睡眠的模仿不同于真正的睡眠函数,因为它不会阻塞线程。它只是JavaScript当前setTimeout函数之上的糖。这种功能类型已经在Task.js中实现,现在应该可以在Firefox中使用。
这里大多数解决方案的问题是它们倒带堆栈。在某些情况下,这可能是一个大问题。在这个例子中,我展示了如何以不同的方式使用迭代器来模拟真实的睡眠。
在本例中,生成器正在调用自己的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");
}