有没有比下面的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");
}
需要使用“休眠”方法的对象的方法,如下所示:
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”的调用者不能依赖于此。由于“睡眠”方法不存在,我使用后一种方法并相应地设计代码。
对于浏览器,我同意使用setTimeout和setInterval。
但是对于服务器端代码,它可能需要一个阻塞函数(例如,这样可以有效地进行线程同步)。
如果您正在使用Node.js和Meteor,您可能遇到了在光纤中使用setTimeout的限制。下面是服务器端睡眠的代码。
var Fiber = require('fibers');
function sleep(ms) {
var fiber = Fiber.current;
setTimeout(function() {
fiber.run();
}, ms);
Fiber.yield();
}
Fiber(function() {
console.log('wait... ' + new Date);
sleep(1000);
console.log('ok... ' + new Date);
}).run();
console.log('back in main');
参见:Node.js光纤,睡眠
有一个新的库Sequencr.js,它将函数与超时巧妙地链接在一起,这样就可以避免回调。
结果是:
setTimeout(function(timeout){
function1();
setTimeout(function(timeout){
function2();
setTimeout(function(timeout){
function3();
}, timeout, timeout)
}, timeout, timeout)
}, 10, 10);
在这方面:
Sequencr.chain([function1, function2, function3], 10);
并且内置支持在每次迭代之间“休眠”的循环。