gpt4 book ai didi

javascript - 如何在 JavaScript 循环中添加延迟?

转载 作者:IT老高 更新时间:2023-10-28 11:05:23 24 4
gpt4 key购买 nike

我想在 while 循环中添加延迟/ sleep :

我试过这样:

alert('hi');

for(var start = 1; start < 10; start++) {
setTimeout(function () {
alert('hello');
}, 3000);
}

只有第一种情况为真:显示alert('hi')后,等待3秒后显示alert('hello')但随后 alert('hello') 会不断重复。

我想要的是 alert('hello')alert('hi') 3 秒后显示之后,然后它需要等待 3 秒第二次 alert('hello') 以此类推。

最佳答案

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

关于javascript - 如何在 JavaScript 循环中添加延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3583724/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com