我想在while
循环中添加一个延迟/休眠:
我是这样尝试的:
alert('hi');
for(var start = 1; start < 10; start++) {
setTimeout(function () {
alert('hello');
}, 3000);
}
只有第一种情况是正确的:在显示alert('hi')
之后,它将等待3秒,然后alert('hello')
将被显示,但随后alert('hello')
将不断重复。
我想要的是,在alert('hi')
之后3秒显示alert('hello')
之后,第二次显示alert('hello')
需要等待3秒,依此类推。
发布于 2010-08-27 19:38:39
setTimeout()
函数是非阻塞的,并将立即返回。因此,您的循环将非常快速地迭代,并且将快速连续地一个接一个地启动3秒超时触发器。这就是为什么你的第一个警报会在3秒后弹出,而其他所有警报都会相继出现,没有任何延迟。
您可能希望使用下面这样的内容:
var i = 1; // set your counter to 1
function myLoop() { // create a loop function
setTimeout(function() { // call a 3s setTimeout when the loop is called
console.log('hello'); // your code here
i++; // increment the counter
if (i < 10) { // if the counter < 10, call the loop function
myLoop(); // .. again which will trigger another
} // .. setTimeout()
}, 3000)
}
myLoop(); // start the loop
您还可以通过使用自调用函数,将迭代次数作为参数传递来整理它:
(function myLoop(i) {
setTimeout(function() {
console.log('hello'); // your code here
if (--i) myLoop(i); // decrement i and call myLoop again if i > 0
}, 3000)
})(10); // pass the number of iterations as an argument
发布于 2010-08-27 19:40:23
尝试如下所示:
var i = 0, howManyTimes = 10;
function f() {
console.log("hi");
i++;
if (i < howManyTimes) {
setTimeout(f, 3000);
}
}
f();
发布于 2017-04-05 14:56:47
这将会起作用
for (var i = 0; i < 10; i++) {
(function(i) {
setTimeout(function() { console.log(i); }, 100 * i);
})(i);
}
试试这个小提琴:https://jsfiddle.net/wgdx8zqq/
https://stackoverflow.com/questions/3583724
复制相似问题