Using setInterval, I made a timer which has countdown of 5 minutes. It is actived by button-click. When it reaches 0 minutes and 0 seconds, timer will be automatically stopped and performed some other actions.
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);
});
Timer runs out and actions performed. Here is everything ok. But I can't find a way to stop/freeze timer by button click. I need something like (I know it is wrong, but as an example):
function testDone(ClOCK)
{
clearInterval(CLOCK);
// GO LEFT;
}
<button id="send_quiz" onclick="testDone(CLOCK)" type="submit">Done!</button>
or
document.getElementById('send_quiz').addEventListener("click", testDone);
Neither idea is functional.
Does anyone have an idea?