gpt4 book ai didi

javascript - do while 循环中的 setTimeout

转载 作者:行者123 更新时间:2023-11-30 08:32:12 25 4
gpt4 key购买 nike

我尝试每 2 秒输出一个带有消息“hello”的警告框,但只有 5 次。所以我写了这段代码:

var counter = 1;

do {
setTimeout
(
function()
{
alert("hello");
counter++;
},
2000
);
} while( counter <= 5 );

但是我的页面每次都崩溃?为什么?在警报之间添加 2000 毫秒延迟的最佳方法是什么?

最佳答案

But my page crashes everytime? Why?

因为计数器仅在回调内部递增 - 循环可能会尝试在这段时间内运行数千次(如果不是数万次的话)并快速运行浏览器内存不足。更准确地说,正如评论中指出的那样,循环永远不会放弃对 setTimeout 调用的控制 - 所以它永远不会运行(不要太担心这里的区别 - 只需接受你的计数器没有增加)

Whats the best way to add a delay of 2000ms between the alerts

只有在前一个结束时才开始下一个。

function showHello(i){
if(i<5){
setTimeout
(
function()
{
alert("hello");
showHello(i+1)
},
2000
);
}
}

showHello(0);

相关:Is it possible to chain setTimeout functions in Javascript?how to make a setInterval stop after some time or after a number of actions?

关于javascript - do while 循环中的 setTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36014311/

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