admin管理员组

文章数量:1405301

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

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

Share edited Jun 27, 2020 at 19:15 VLAZ 29.2k9 gold badges63 silver badges84 bronze badges asked Jun 27, 2020 at 19:13 user11092493user11092493 1
  • Is because when you enter the Interval, you cannot exit, so the scipt will never return at the else – Matteo Possamai Commented Jun 27, 2020 at 19:28
Add a ment  | 

1 Answer 1

Reset to default 9

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

本文标签: javascriptSet and clear interval conditionallyStack Overflow