且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带有启动&的javascript倒数计时器停止按钮

更新时间:2023-12-04 08:38:16

在这里,您只需要使 myTimer 全局。我还修复了重置计时器后不会显示5的故障。

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>