我想在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'),以此类推。
下面是我如何创建一个无限循环的延迟,在特定条件下中断:
// 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。
下面是我用来循环数组的函数:
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
}
因为ES7有一个更好的方法来等待循环:
// Returns a Promise that resolves after "ms" Milliseconds
const timer = ms => new Promise(res => setTimeout(res, ms))
async function load () { // We need to wrap the loop into an async function for this to work
for (var i = 0; i < 3; i++) {
console.log(i);
await timer(3000); // then the created Promise can be awaited
}
}
load();
当引擎到达await部分时,它设置一个超时并停止async函数的执行。然后,当超时完成时,继续执行。这是非常有用的,因为你可以延迟(1)嵌套循环,(2)有条件的,(3)嵌套函数:
异步函数任务(i) {// 3
等待计时器(1000);
console.log('任务${i}完成! ');
}
异步函数main() {
对于(设I = 0;I < 100;I += 10) {
For(令j = 0;J < 10;j++) {// 1
如果(j % 2) {// 2
等待任务(i + j);
}
}
}
}
main ();
函数定时器(ms){返回新的承诺(res => setTimeout(res, ms));}
MDN参考资料
虽然ES7现在被NodeJS和现代浏览器支持,但你可能想用BabelJS编译它,这样它就可以在任何地方运行。