I started building a countdown timer. Thus far it is mostly working as I want. A button will either start or pause the timer. However if I start and pause it more than once, the interval will no longer remain set to 1000ms. This makes me think that it is now running multiple intervals in parallel per button click. I'm not sure how exactly to fix this or where exactly the problem is.
function startCountDown() {
running = !running;
running ? startButton.value = "Stop Countdown" : startButton.value = "Start Countdown";
let t = timeDisplay.innerHTML.replace(/:/g, '');
let seconds = t.slice(-2)
let minutes = t.slice(-4, -2);
let hours = t.slice(-6, -4);
seconds > 60 ? seconds = 59 : seconds;
minutes > 60 ? minutes = 59 : minutes;
secondsRemaining = (hours * 3600) + (minutes * 60) + (seconds * 1)
intervalHandle = setInterval(tick, 1000)
if (running === false) {
clearInterval(intervalHandle)
}
}
function tick() {
if (running) {
secondsRemaining--;
console.log(secondsRemaining)
hour = Math.floor(secondsRemaining / 3600)
min = Math.floor((secondsRemaining - (hour * 3600)) / 60);
sec = Math.floor((secondsRemaining - (hour * 3600) - (min * 60) ));
timeDisplay.innerHTML = `${hour}:${min}:${sec}`
if (secondsRemaining === 0 || running === false) {
clearInterval(intervalHandle)
}
}
}
In the lines
intervalHandle = setInterval(tick, 1000)
if (running === false) {
clearInterval(intervalHandle)
}
you start a new timer everytime startCountDown
is called. So, if there was a running timer before, you loose its ID, because the new timer's ID is stored in intervalHandle
. Then, if running
flag is false
, you just stop the newly created timer, the previous one keeps running forever.
In other words, you leak a timer with every second call to startCountDown
.
You should rewrite the code to something like
if (running === false) {
clearInterval(intervalHandle);
} else {
intervalHandle = setInterval(tick, 1000);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.