如何停止并重置倒数计时器?

时间:2020-01-31 06:31:54

标签: javascript

我需要显示一个从10开始的倒数计时器。只要我在运行时单击任意按钮,计数器就会再次重置。下面的功能运行良好,但是每当我在计数过程中单击按钮时,计时器就会快速转发并且显示得太快。

var timeleft = 10;
var downloadTimer = setInterval(function() {
  document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
  timeleft -= 1;
  if (timeleft <= 0) {
    clearInterval(downloadTimer);
  }
}, 1000);

function fn_start() {
  var timeleft = 10;
  var downloadTimer = setInterval(function() {
    document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
    timeleft -= 1;
    if (timeleft <= 0) {
      clearInterval(downloadTimer);
    }
  }, 1000);
}
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

<div id="countdown"></div>
<button type='button' id='startbtn' onclick="fn_start()">Start</button>

1 个答案:

答案 0 :(得分:1)

每次调用函数时都需要清除间隔。

<div id="countdown"></div>
<button type='button' id='startbtn' onclick="fn_start()">Start</button>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
  var downloadTimer; // global var
  
  function fn_start() {
    var timeleft = 10;
    
    clearInterval(downloadTimer);
    
    downloadTimer = setInterval(function() {
      document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
      timeleft -= 1;
      if (timeleft <= 0) {
        clearInterval(downloadTimer);
      }
    }, 1000);
  }
  // If you don't need to show the timer first, comment this line
  fn_start();
</script>