使用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;
}
});
只需在函数外部声明minute和sec变量。 当您单击start按钮时,您的函数将从函数外部获取值。
这意味着javascript在函数结束时从不保存值,就是这样。。。