使用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
变量移动到外部作用域,以便所有函数都可以访问它。
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;
}
});
关于javascript - 当时间用完时,通过单击按钮或停止来停止/卡住计时器(setInterval),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62557640/