再次按下按钮时开始新的间隔

Start a new interval when a button is pressed again

我的查询很简单。我能够制作一个倒计时脚本,所以当单击一个按钮时,倒计时开始;然而,如果我们继续点击按钮,它只会添加另一个倒计时,并且也会弄乱原来的倒计时。我试图清除间隔,但不确定是什么导致它 运行。当我按下 Start 时,倒计时开始,但如果您再次单击它,那么您可以自己尝试一下。我也无法弄清楚停止按钮如何结束间隔计时器,我已经尝试过 cleartInterval();还有。

$("#startClock").click( function(){
     var counter = document.getElementById('minutes').value;
   setInterval(function() {
     counter--;
      if (counter >= 0) {
         span = document.getElementById("count");
         span.innerHTML = counter;
      }
      if (counter === 0) {
        span = document.getElementById("count");
         span.innerHTML = "";
       }
     },  1000);


});
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js?ver=4.1'></script>
Minutes
<select id="minutes">
  <option value="60">1</option>
  <option value="120">2</option>
  <option value="180">3</option>
  <option value="240">4</option>
  <option value="300">5</option>
  </select>
<button id=startClock >Start</button>
<button id=stopClock >Stop</button> <br/> 
<div id="count"></div>

试试这个:

var clickTimer;

$("#startClock").click( function(){
     if (clickTimer) {
        clearInterval(clickTimer);
     }
     var counter = document.getElementById('minutes').value;
     clickTimer = setInterval(function() {
     counter--;
      if (counter >= 0) {
         span = document.getElementById("count");
         span.innerHTML = counter;
      }
      if (counter === 0) {
        span = document.getElementById("count");
         span.innerHTML = "";
       }
     },  1000);


});

编辑

$("#stopClock").click( function(){
 if (clickTimer) {
    clearInterval(clickTimer);
    clickTimer = undefined;
 }
});