javascript countdown timer with start & stop buttons

前端 未结 4 740
孤城傲影
孤城傲影 2021-01-06 02:29

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.

4条回答
  •  醉酒成梦
    2021-01-06 02:46

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

    5

提交回复
热议问题