Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set and clear interval conditionally

Tags:

javascript

I want to stop interval after it reaches 0, but it goes on and on...

here is my code

function timer() {
  var health = 100;
  var counter = 0;
  if (health > 0) {
    counter = setInterval(function () {
      reduce = Math.floor(Math.random() * 15);
      health = health - reduce;
      console.log(health);
    }, 1000);
  } else {
    clearInterval(counter);
  }
}

1 Answers

Do the check and conditional clearInterval inside the scheduled function:

function timer() {
  var health = 100;
  var counter = setInterval(function () {
   var reduce = Math.floor(Math.random() * 15);
   health = health - reduce;
   console.log(health);
   if (health < 0) {
     clearInterval(counter);
   } 
  }, 1000);
}
like image 179
Robin Zigmond Avatar answered Mar 17 '26 13:03

Robin Zigmond



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!