-1

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?

4
  • its not very clear what you are asking Commented Jan 6, 2012 at 14:27
  • @DanielA.White I am asking: How do I get init fired to output to the console only four times? Commented Jan 6, 2012 at 14:30
  • I want to interrupt the setInterval timer based on a certain condition. Commented Jan 6, 2012 at 14:30
  • Change for(i = 0; i < 10; i++) to for(i = 0; i < 4; i++) Commented Jan 6, 2012 at 14:31

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

ah I was looking for that kind of explanation. Now I get it.
2

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.

2 Comments

Yes this does it too. Could you tell me why the i variable needs to be global?
Because when i is set as global only it's value will be undisturbed otherwise, each and every time when init is called it will be set back to zero. So the increment option would have no effect on i

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.