设置超时在循环时执行

setTimeout in do while loop

本文关键字:执行 循环 超时 设置      更新时间:2023-09-26

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

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

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

但是我的页面每次都崩溃?为什么?

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

警报之间添加 2000 毫秒延迟的最佳方法是什么

仅在前一个完成时启动下一个。

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

相关:是否可以在Javascript中链接setTimeout函数?以及如何使setInterval在一段时间或多次操作后停止?

改用 setInterval:

var counter = 0; // setting the counter
var interval = setInterval(function(){ //setInterval does repeatedly what setTimeout only
                                       //does once
    counter++;
    if(counter === 5){
        clearInterval(interval); //if the counter reaches 5 (the times you asked
                                 //for repeating the alert box) you clear the interval,
                                 //stopping the loop
    }
    alert("hello");
}, 2000);

这是一个工作小提琴:https://jsfiddle.net/mwosm34x/

请改用setInterval

当计数器大于 5 时clearInterval()

var counter = 1;
var timer = setInterval(function () {
  alert("hello "+counter);
  counter++;
  if (counter > 5) {
    clearInterval(timer);
  }
}, 2000);