带有启动&的javascript倒数计时器停止按钮
问题描述:
我需要使用从5到0的简单倒数计时器,并使用按钮开始和停止计数器。我唯一不知道的是为什么我的计数器不会停止。
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.
代码如下:
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>
答
在这里,您只需要使 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>