[英]Stop/freeze timer (setInterval) by button click or stop, when time ran out
使用setInterval
,我制作了一个倒计时 5 分钟的计时器。 它是通过单击按钮激活的。 当达到 0 分 0 秒时,定时器会自动停止并执行一些其他动作。
document.addEventListener("DOMContentLoaded", function (event) {
function runTimer(){
const CLOCK = setInterval(function () {
let minute = 4;
let sec = 59
document.getElementById("timer").innerHTML = (sec < 10) ? '0' + minute + ":" + '0' + sec
: '0' + minute + ":" + sec;
if (sec != -1) {
sec--;
}
// if time 0 minutes 0 seconds, stop timer
if (minute == 0 && sec == -1) {
document.getElementById("timer").innerHTML = '00:00';
stopTimer(CLOCK);
}
if (sec == -1) {
sec = 59;
if (minute != 0) {
minute--;
} else {
sec = -1;
}
}
}, 1000);
}
function stopTimer(CLOCK)
{
clearInterval(CLOCK);
// GO RIGHT;
}
document.getElementById('start-test').addEventListener("click", runTimer);
});
计时器用完并执行操作。 这里一切正常。 但是我找不到通过单击按钮来停止/冻结计时器的方法。 我需要类似的东西(我知道这是错误的,但作为一个例子):
function testDone(ClOCK)
{
clearInterval(CLOCK);
// GO LEFT;
}
<button id="send_quiz" onclick="testDone(CLOCK)" type="submit">Done!</button>
或者
document.getElementById('send_quiz').addEventListener("click", testDone);
这两个想法都不起作用。
有人有想法吗?
您需要将CLOCK
变量移动到外部 scope ,所有函数都可以访问它。
document.addEventListener("DOMContentLoaded", function (event) {
let CLOCK;
function runTimer(){
CLOCK = setInterval(function () {
let minute = 4;
let sec = 59
document.getElementById("timer").innerHTML = (sec < 10) ? '0' + minute + ":" + '0' + sec
: '0' + minute + ":" + sec;
if (sec != -1) {
sec--;
}
// if time 0 minutes 0 seconds, stop timer
if (minute == 0 && sec == -1) {
document.getElementById("timer").innerHTML = '00:00';
stopTimer(CLOCK);
}
if (sec == -1) {
sec = 59;
if (minute != 0) {
minute--;
} else {
sec = -1;
}
}
}, 1000);
}
function stopTimer(CLOCK)
{
clearInterval(CLOCK);
// GO RIGHT;
}
document.getElementById('start-test').addEventListener("click", runTimer);
document.getElementById('send_quiz').addEventListener("click", testDone);
function testDone()
{
clearInterval(CLOCK);
// GO LEFT;
}
});
只需从 function 外部声明您的分钟和秒变量。 当您单击开始按钮时,您的 function 将从 function 外部获取值。
这意味着 javascript 永远不会在 function 结束时保持值,就是这样......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.