首页 > 解决方案 > 有条件地设置和清除间隔

问题描述

我想在它达到0后停止间隔,但它会一直持续......

这是我的代码

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

标签: javascript

解决方案


clearInterval在预定函数中执行检查和条件:

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

推荐阅读