为什么clearInterval()函数没有停止javascript计时器?

时间:2015-09-12 03:34:52

标签: javascript jquery

我正在尝试创建一个基本的番茄钟,我在开始时卡住了,计时器没有停止到0,我的代码出现问题在哪里?

$(document).ready(function() {
    var targetTime, intervalID;
    $('button').on('click', function() {
        targetTime = Date.now() + (1 * 60 * 1000);
        intervalID = setInterval(timer, 1000, targetTime, intervalID);
    });
    // timer callback for setInterval function
    function timer(targetTime, intervalID) {
        var secondsLeft = Math.ceil((targetTime - Date.now()) / 1000);
        $('h1').text(secondsLeft);
        if (secondsLeft <= 0)
            clearInterval(intervalID);
    }
});
<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Pomodoro Clock</title>
   </head>
   <body>
      <h1></h1>
      <button>start</button>
      <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
   </body>
</html>

2 个答案:

答案 0 :(得分:4)

尝试将targetTime, intervalID用作全局而不是传递

试试这个

$(document).ready(function() {
  var targetTime, intervalID;
  $('button').on('click', function() {
    clearInterval(intervalID);
    targetTime = Date.now() + (1 * 60 * 1000);
    intervalID = setInterval(timer, 1000);
  });
  // timer callback for setInterval function
  function timer() {
    var secondsLeft = Math.ceil((targetTime - Date.now()) / 1000);
    $('h1').text(secondsLeft);
    if (secondsLeft <= 0)
      clearInterval(intervalID);
  }
});
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Pomodoro Clock</title>
</head>

<body>
  <h1></h1>
  <button>start</button>
  <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</body>

</html>

答案 1 :(得分:1)

你有一个参数,它在你的计时器功能中设置为'undefined',删除它并且它正常工作

$(document).ready(function() {
  var targetTime, intervalID;
  $('button').on('click', function() {
    targetTime = Date.now() + (1 * 60 * 1000);
    intervalID = setInterval(timer, 1000);
  });
  // timer callback for setInterval function
  function timer() {
    var secondsLeft = Math.ceil((targetTime - Date.now()) / 1000);
    $('h1').text(secondsLeft);
    if (secondsLeft <= 0)
      clearInterval(intervalID);
  }
});
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Pomodoro Clock</title>
</head>

<body>
  <h1></h1>
  <button>start</button>
  <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</body>

</html>