Lorna Roberts
Lorna Roberts

Reputation: 33

How can I get clearInterval to stop my timer?

I have 2 timers I want to run seperately. 'timer'is linked to the first function 'timePassed' and should count up until the vital stats of my creature go down to 0 then it should stop. It does. However, my second timer, 'timer2' is linked to the second function 'restart'. It isn't stopping when the stats reach 0, which is want I want. Just like the first.

I suspect it might have to do with my running of 'timePassed'(function 1) within function 2 'restart'. I feel the timer runs too fast for 1 second intervals so that's another clue. But I'm not sure as I'm new to all this. Basically, how can I stop 'timer2' as soon as the stats reach 0?

//first function that works fine

function timePassed(){
    message();
    screen();
    i++;
    answer();
    decrease();
    changeStar();
    changeDonut();
    changeHeart();
    if (health === 0 || happiness === 0 || hunger === 0){      
      dodo();
     clearInterval(timer);
          }
  }var timer= setInterval(timePassed, 1000);

//second function whose timer isn't working correctly

 function restart() {
   i=0;
   message();
   health = 4;
   happiness = 4;
   hunger = 4;
   screen();
   timePassed();
   if (health === 0 || happiness === 0 || hunger === 0){      
      dodo();
       clearInterval(timer2);    
      }
    } var timer2 = setInterval(timePassed, 1000);

I've tried assigning var timer2 to both timePassed() (as shown) and restart(). If I use restart(), my counter bounces up and down never decreasing enough to trigger the clearInterval.

If I remove the 'if' statement from restart(), and/or timer2, restart() just sits and doesn't count down.

Upvotes: 2

Views: 245

Answers (1)

Coldark
Coldark

Reputation: 445

After some thought here are the issues you're facing:

  • restart() will never enter its if block, because you're reassigning variables it checks beforehand, that's why second interval will never get cleared
  • you're running two exact same timers, so every second timePassed() is called twice
  • you're calling timePassed() again in restart() which not necessarily is causing problems, but for sure it increases value of i right after you set it up to 0 (the bouncing counter issue)

So, answering your question - to stop timer2 as soon as stats reach 0, you can simply move clearInterval(timer2) to the if block inside timePassed() and i.e call timePassed() before you reset stats and counter, or just clear both intervals in restart() without calling timePassed(). It all means though that you'll be clearing both intervals which may not be what you want.

However looking at the code you provided, running two exact same timers doesn't make much sense - you could just run one timer with half of the delay and achieve pretty much the same result.

Upvotes: 2

Related Questions