I would have liked to know how to display a message at the end of my timer for a certain time (1 minutes) and then loop again.
Example of the desired process:
Thanks you, Quentin S.
I have already realized the timer but I miss more than the monitor tag is replaced by the message I want to put for 1 minute before starting the process from the beginning
<div><span id="time">02:00</span></div>
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);
}
window.onload = function () {
var twoMinutes = 60 * 2,
display = document.querySelector('#time');
startTimer(twoMinutes, display);
};
I'd do this by stopping the interval once the time has reached zero and restarting it after one minute using setTimeout
By the way, your code has a little bug, the callback provided for setInterval
does not run when the interval starts, but only after one interval (one second in your case). I've fixed that here.
Also I have adjusted the times to reduce waiting.
function startTimer(duration, display, pause) {
var timer = duration, minutes, seconds;
const updateTime = 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;
display.textContent = "wait...";
clearInterval(intervalId);
setTimeout(function () {
startTimer(duration, display, pause)
}, pause*1000)
}
}
const intervalId = setInterval(updateTime, 1000);
updateTime();
}
window.onload = function () {
var interval = 4,
display = document.querySelector('#time');
startTimer(interval, display, 2);
};
<div><span id="time">XX:XX</span></div>