I'm setting up a countdown timer to an application, and when this countdown hits the mark of 00:00 I want to have 5 seconds of delay before it restarts counting down again. How can i use setTimeout() to make it?
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
duration = timer;
}
The interval will continue ticking until you clear it, so what you need to do is when the timer hits zero, clear the interval and then set a timeout that will restart the interval. (In order to clear an interval, you need to store its returned handle in a variable first.) A bit of recursion can help here:
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var timerInterval = setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
window.clearInterval(timerInterval);
window.setTimeout(() => startTimer(duration, display), 5000);
}
}, 1000);
}