javascript停止重复的setTimeout函数

时间:2015-12-14 14:00:38

标签: javascript

我有一个功能,作为倒计时器,用于建造一个简单的番茄钟。现在我想在用户单击重置功能时停止此功能。我虽然传递了一个简单的if语句,它返回一些东西,因此在倒计时再次迭代之前终止函数,但函数继续运行。知道在这里发生了什么是值得赞赏的。下面的代码也可以在codepen上查看整个内容。

  function countdown(blocker) {
    if (blocker === true) {
      return true;
    } 
    else {
      setTimeout(function() {
        time -= 1;
        updateTimer();
        if (time > 0) {
          countdown();
        }
      }, 1000);
    }
  }

调用这样的函数一旦开始就不会停止它:

countdown(true);

2 个答案:

答案 0 :(得分:0)

setIntervalclearInterval一起使用。

  var si = -1;
  var countdown = function() {
    si = setInterval(function() {
      time -= 1;
      updateTimer();
      if (time <= 0) {
        clearInterval(si);
      }
    }, 1000);
  };

  //Where button is the reference to a button existing in your html page
  button.onclick = function() {
    clearInterval(si);

    //reset info here
    timer = 2000;
    countdown();
  }

答案 1 :(得分:0)

请不要 使用setInterval,如KФ所建议的那样,但您需要使用clearTimeout清除超时。确保存储对超时对象的引用:

timeout = setTimeout(/* arguments */);

添加重置功能并在重置时使用它:

function reset () {

  if(timeout)
    clearTimeout(timeout);

  time = 1500;

}

此处your Pen已更新。

相关问题