Amit Erandole
Amit Erandole

Reputation: 12281

Why is my javascript for loop not working?

fourI am writing a javascript for loop and am sure have done a terrible job:

init = function () {

    var i = 0;

    timer = setInterval(function () {

        if (i >= 4) {
            clearInterval(timer);
            return;
        }

        for (i = 0; i < 10; i++) {
            console.log('init fired');
        }

    }, 2000);

};

init();

What I want is for the timer to stop after the i variable in the for loop reaches four. Instead the log is showing init fired ten times. What am I doing wrong?

Upvotes: -1

Views: 4641

Answers (2)

AmGates
AmGates

Reputation: 2123

I think you need it like this

var i=0; //Global Declaration
init = function(){  

    timer = setInterval(function(){
          console.log('init fired');
          i++;
      if(i>4){
      clearInterval(timer);
      return; }

  }, 2000);

};

init();

Hope this solves your problem. This will trigger init() method four times as you have expected and if the i reaches 4 the interval will be cleared.

Upvotes: 2

Pointy
Pointy

Reputation: 414006

Every time the timeout handler runs, it starts "i" back at zero.

The problem with your "for" loop is basically that you should not use a "for" loop :-)

Those 10 iterations are happening on the first pass through the function. After that first pass, "i" will be 10 and so the "if" condition will cancel the timeout. However, that "if" check is only made at the beginning of the function, so the loop will always complete 10 iterations.

If you want to have just four iterations of the timer (or five or whatever), you'd just leave off the "for" loop, and add i++; after the console log message. That way, the timer would issue one log output when it runs, and when that's happened the number of times you desire, it will stop.

Upvotes: 2

Related Questions