Search code examples
javascriptcountdown

Start a new interval when a button is pressed again


My query is fairly simple. I was able to make a countdown script, so when a button is clicked the countdown begins; however, if we keep clicking the button it just adds another countdown and mess the original one too. I tried to clear the interval, but not sure what does not make it run. When I press Start the countdown begins, but if you click on it again, well you can try it yourself. I am also not able to figure out how a stop button can end the interval timer and I have tried cleartInterval(); as well.

$("#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>


Solution

  • Try this:

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

    EDIT

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