简体   繁体   中英

setTimeout in do while loop

I try to output an alert box with the message "hello" every 2 seconds, but only 5 times. So I wrote this code:

var counter = 1;

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

But my page keeps crashing everytime? Why? Whats the best way to add a delay of 2000ms between the alerts?

But my page crashes everytime? Why?

Because the counter is only incremented inside the callback - the loop probably tries to run thousands (if not tens of thousands) of times in that time and quickly runs the browser out of memory. More accurately, as is pointed out in comments, the loop never gives up control to the setTimeout call - so that is never going to get run (Dont worry too much about the distinction here - just accept that your counter is not being incremented)

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

Kick off the next one only as the previous one finishes.

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

showHello(0);

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

Use setInterval instead:

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

Here's a working fiddle: https://jsfiddle.net/mwosm34x/

Use setInterval instead.

And clearInterval() when the counter is greater than 5.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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