繁体   English   中英

setTimeout在do while循环中

[英]setTimeout in do while loop

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

var counter = 1;

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

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

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

由于计数器仅在回调内部递增-循环可能会尝试在该时间内运行数千次(如果不是几万次),并迅速使浏览器内存不足。 就像注释中指出的那样,更准确地说,循环永远不会放弃对setTimeout调用的控制-这样就永远不会运行(不要太担心这里的区别-只需接受您的计数器没有被递增)

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

仅在上一个完成时才开始下一个。

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); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM