Search code examples
javascriptcountercountdowncountdowntimer

Why won't my countdown timer start and stop?


I need to make a simple countdown timer from 5 to zero, with the buttons to START and STOP the counter. The only thing that I don't know is that why won't my counter stop.

The code is presented below:

   function clock() {
     var myTimer = setInterval(myClock, 1000);
     var c = 5;

     function myClock() {
       document.getElementById("demo").innerHTML = --c;
       if (c == 0) {
         clearInterval(myTimer);
         alert("Reached zero");
       }
     }
   }
<p id="demo">5</p>
<button onclick="clock()">Start counter</button>
<button onclick="clearInterval(myTimer)">Stop counter</button>


Solution

  • Here you go, you just needed to make myTimer global. I also fixed a glitch where after resetting the timer, it won't show 5.

    var myTimer;
       function clock() {
         myTimer = setInterval(myClock, 1000);
         var c = 5;
    
         function myClock() {
           document.getElementById("demo").innerHTML = --c;
           if (c == 0) {
             clearInterval(myTimer);
             alert("Reached zero");
           }
         }
       }
    <p id="demo">5</p>
    <button onclick="clock(); document.getElementById('demo').innerHTML='5';">Start counter</button>
    <button onclick="clearInterval(myTimer);">Stop counter</button>