Black
Black

Reputation: 20212

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?

Upvotes: 2

Views: 5107

Answers (3)

Munawir
Munawir

Reputation: 3356

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

Upvotes: 0

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/

Upvotes: 0

Jamiec
Jamiec

Reputation: 136094

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?

Upvotes: 6

Related Questions