'Countdown won't stop at 0, keeps decrementing
I have a timer that keeps decrementing after 0 so I get negative numbers. Time starts when a button is clicked and the pauses when the same button is clicked again.
button.addEventListener("click", function(event){
console.log('timer started')
// Timer paused, click to start
// Pause/Play Timer
if(timeleft == 90){
timeleft = setInterval(function() {
time--;
timerDisplay.innerHTML = time;
}, 1000);
} else if (timeleft === 0) {
clearInterval(timeleft);
} else{
// Timer running, click to pause
console.log('timer paused')
clearInterval(timeleft);
timeleft = 90;
}
});
The stop and start functionality works fine but why won't it stop counting down once it reaches 0?
Solution 1:[1]
Sample code for reference to build a timer.
const actionBtn = document.getElementById("start-timer");
let isTimerRunning = false;
let interval = null;
let maxTime = 20;
// Click handler to start and stop timer button in DOM
actionBtn.addEventListener("click", function() {
if(isTimerRunning) {
// stop timer
stopTimer();
} else {
// start timer
startTimer();
}
});
// Function to start timer
function startTimer() {
isTimerRunning = true; // toggle state, so on click again we can stop timer
// 1sec interval function to reduce max time
interval = setInterval(function() {
maxTime = maxTime - 1;
if(maxTime > -1) { // if the more time left (more than 0) update UI
renderUi(`Reset (${maxTime}sec)`);
} else { // if there is no time left stop timer
stopTimer();
}
}, 1000);
}
// stop timer
function stopTimer() {
isTimerRunning = false; // toggle state, so on click again we can start timer
clearInterval(interval); // clear the interval
maxTime = 20; // reset max time to initial value
renderUi(`Start Timer (${maxTime}sec)`); // update UI to initial value
}
// A generic function to update UI
// if we have complet UI structure we can update this function
function renderUi(str) {
actionBtn.innerText = str;
}
<button id="start-timer">Start Timer (20sec)</button>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
