我想在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'),以此类推。
据我所知,setTimeout函数是异步调用的。你能做的是将整个循环包装在一个异步函数中,并等待一个包含setTimeout的Promise,如下所示:
var looper = async function () {
for (var start = 1; start < 10; start++) {
await new Promise(function (resolve, reject) {
setTimeout(function () {
console.log("iteration: " + start.toString());
resolve(true);
}, 1000);
});
}
return true;
}
然后像这样调用运行它:
looper().then(function(){
console.log("DONE!")
});
请花些时间好好理解异步编程。
在ES6 (ECMAScript 2015)中,您可以使用生成器和间隔迭代延迟。
生成器(generator)是ECMAScript 6的一个新特性,是可以被替换的函数
顿了顿,接着说。调用genFunc不会执行它。相反,它
返回一个所谓的生成器对象,让我们控制genFunc的
执行。genFunc()最初是挂起在它的开始
的身体。方法genObj.next()继续执行genFunc,
直到下一次丰收。
(探索ES6)
代码示例:
Let arr = [1,2,3, 'b'];
let genObj = genFunc();
let val = genObj.next();
console.log (val.value);
let interval = setInterval(() => {
val = genObj.next();
If (val.done) {
clearInterval(间隔);
}其他{
console.log (val.value);
}
}, 1000);
函数* genFunc() {
For (let item of arr) {
收益项;
}
}
所以如果你正在使用ES6,这是实现延迟循环的最优雅的方式(在我看来)。
下面是我如何创建一个无限循环的延迟,在特定条件下中断:
// 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。
对于常用的“忘记正常循环”和使用这个组合的“setInterval”包括“setTimeOut”:像这样(从我的实际任务)。
function iAsk(lvl){
var i=0;
var intr =setInterval(function(){ // start the loop
i++; // increment it
if(i>lvl){ // check if the end round reached.
clearInterval(intr);
return;
}
setTimeout(function(){
$(".imag").prop("src",pPng); // do first bla bla bla after 50 millisecond
},50);
setTimeout(function(){
// do another bla bla bla after 100 millisecond.
seq[i-1]=(Math.ceil(Math.random()*4)).toString();
$("#hh").after('<br>'+i + ' : rand= '+(Math.ceil(Math.random()*4)).toString()+' > '+seq[i-1]);
$("#d"+seq[i-1]).prop("src",pGif);
var d =document.getElementById('aud');
d.play();
},100);
setTimeout(function(){
// keep adding bla bla bla till you done :)
$("#d"+seq[i-1]).prop("src",pPng);
},900);
},1000); // loop waiting time must be >= 900 (biggest timeOut for inside actions)
}
PS:理解(setTimeOut)的真实行为:它们都将在同一时间开始“三个bla bla bla将在同一时刻开始倒数”,因此设置不同的超时来安排执行。
PS 2:计时循环的例子,但对于一个反应循环,你可以使用事件,承诺async await ..
const autoPlayer = (arr = [1, 2, 3, 4, 5]) => {
// Base case:
if (arr.length < 1) return
// Remove the first element from the array.
const item = arr.shift()
// Set timout
setTimeout(() => {
console.log('Hello, world!', item) // Visualisation.
autoPlayer() // Call function again.
}, 1000) // Iterate every second.
}
Hey, I know this post is very old, but this code "loops" and adds a delay to it using a recursive method. I don't think you can 'actually' delay a loop itself from iterating based on reading various comments from other people. Maybe this can help someone out! Basically the function accepts an array (in this example). On each iteration the setTimeout Javascript method is called. The function calls itself again indefinitely when the timer of the setTimeout function expires, but on each call the array becomes smaller until it reaches the base-case. I hope this can help anyone else out.