我想在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'),以此类推。
下面是我用来循环数组的函数:
function loopOnArrayWithDelay(theArray, delayAmount, i, theFunction, onComplete){
if (i < theArray.length && typeof delayAmount == 'number'){
console.log("i "+i);
theFunction(theArray[i], i);
setTimeout(function(){
loopOnArrayWithDelay(theArray, delayAmount, (i+1), theFunction, onComplete)}, delayAmount);
}else{
onComplete(i);
}
}
你可以这样使用它:
loopOnArrayWithDelay(YourArray, 1000, 0, function(e, i){
//Do something with item
}, function(i){
//Do something once loop has completed
}
非常简单的单行解决方案,具有实际的异步等待延迟(没有排队setTimeout):
下面的(自动执行匿名)函数在循环之间创建一个实际的延迟,而不是具有不同超时的多个settimeout,这可能会弄乱内存。
在100个循环中的每一个循环中,它都等待一个新的承诺来解决。
这只发生在setTimeout '允许'它在90ms后。在此之前,代码将被async-await / pending Promise阻塞。
(async () => {
For(令i=0;我< 100;我+ +){
等待新的承诺((resolve) => {setTimeout(() =>{文档。我写(“${}”);解决(true)}, 90)});
}
})()