我想在while循环中添加一个delay/sleep:
我是这样试的:
alert('hi');
for(var start = 1; start < 10; start++) {
setTimeout(function () {
alert('hello');
}, 3000);
}
只有第一种情况是正确的:在显示alert('hi')后,它将等待3秒,然后alert('hello')将显示,但随后alert('hello')将不断重复。
我想要的是,在警报('hello')显示3秒后警报('hi'),然后它需要等待3秒的第二次警报('hello'),以此类推。
我只是想在这里发表我的意见。此函数运行具有延迟的迭代循环。请看这个jsfiddle。函数如下:
function timeout(range, time, callback){
var i = range[0];
callback(i);
Loop();
function Loop(){
setTimeout(function(){
i++;
if (i<range[1]){
callback(i);
Loop();
}
}, time*1000)
}
}
例如:
//This function prints the loop number every second
timeout([0, 5], 1, function(i){
console.log(i);
});
相当于:
//This function prints the loop number instantly
for (var i = 0; i<5; i++){
console.log(i);
}
试试这个
var arr = ['A','B','C'];
(function customLoop (arr, i) {
setTimeout(function () {
// Do here what you want to do.......
console.log(arr[i]);
if (--i) {
customLoop(arr, i);
}
}, 2000);
})(arr, arr.length);
结果
A // after 2s
B // after 2s
C // after 2s
我认为你需要这样的东西:
var TimedQueue = function(defaultDelay){
this.queue = [];
this.index = 0;
this.defaultDelay = defaultDelay || 3000;
};
TimedQueue.prototype = {
add: function(fn, delay){
this.queue.push({
fn: fn,
delay: delay
});
},
run: function(index){
(index || index === 0) && (this.index = index);
this.next();
},
next: function(){
var self = this
, i = this.index++
, at = this.queue[i]
, next = this.queue[this.index]
if(!at) return;
at.fn();
next && setTimeout(function(){
self.next();
}, next.delay||this.defaultDelay);
},
reset: function(){
this.index = 0;
}
}
测试代码:
var now = +new Date();
var x = new TimedQueue(2000);
x.add(function(){
console.log('hey');
console.log(+new Date() - now);
});
x.add(function(){
console.log('ho');
console.log(+new Date() - now);
}, 3000);
x.add(function(){
console.log('bye');
console.log(+new Date() - now);
});
x.run();
注意:使用警报暂停javascript执行,直到你关闭警报。
它的代码可能比您要求的要多,但这是一个健壮的可重用解决方案。
下面是我如何创建一个无限循环的延迟,在特定条件下中断:
// Now continuously check the app status until it's completed,
// failed or times out. The isFinished() will throw exception if
// there is a failure.
while (true) {
let status = await this.api.getStatus(appId);
if (isFinished(status)) {
break;
} else {
// Delay before running the next loop iteration:
await new Promise(resolve => setTimeout(resolve, 3000));
}
}
这里的关键是创建一个通过超时解析的新Promise,并等待它的解析。
显然你需要async/await支持。工作在Node 8。
非常简单的单行解决方案,具有实际的异步等待延迟(没有排队setTimeout):
下面的(自动执行匿名)函数在循环之间创建一个实际的延迟,而不是具有不同超时的多个settimeout,这可能会弄乱内存。
在100个循环中的每一个循环中,它都等待一个新的承诺来解决。
这只发生在setTimeout '允许'它在90ms后。在此之前,代码将被async-await / pending Promise阻塞。
(async () => {
For(令i=0;我< 100;我+ +){
等待新的承诺((resolve) => {setTimeout(() =>{文档。我写(“${}”);解决(true)}, 90)});
}
})()