有没有比下面的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");
}
如果你写一个这样的睡眠函数
var sleep = function(period, decision, callback){
var interval = setInterval(function(){
if (decision()) {
interval = clearInterval(interval);
callback();
}
}, period);
}
你有一个异步函数可以多次调用,
var xhr = function(url, callback){
// Make an Ajax request
// Call a callback when the request fulfils
}
您的项目设置如下:
var ready = false;
function xhr1(){
xhr(url1, function(){ ready = true;});
}
function xhr2(){
xhr(url2, function(){ ready = true; });
}
function xhr3(){
xhr(url3, function(){ ready = true; });
}
然后您可以执行以下操作:
xhr1();
sleep(100, function(){ return done; }, xhr2);
sleep(100, function(){ return done; }, xhr3);
sleep(100, function(){ return done; }, function(){
// Do more
});
而不是像这样无休止的回调缩进:
xhr(url1, function(){
xhr2(url2, function(){
xhr3(url3, function(){
// Do more
});
});
});