I wonder why my countdown didn't stop at 0, the "Time's Up" log are still logging infinitely.
Here's my code:
let timer = 6;
setInterval(function () {
if (timer > 0) {
timer--;
console.log(timer);
} else {
console.log("Time's Up");
clearInterval(timer);
}
}, 1000);
clearInterval needs to know the action you want to cancel. In this case, the action is actually your setInterval, so just assign it to a variable and use that variable as a parameter for clearInterval.
const myInterval = setInterval(() => {
if (timer > 0) {
timer--;
console.log(timer);
} else {
console.log("Time's Up");
clearInterval(myInterval);
}
}, 1000);
What I understand that you are using timer as a variable. So, you are doing one mistake, you are giving wrong parameter inside clearInterval method. You can stop clearInterval method by the code written below:-
NOTE:- I just substitute console.log with document.write to show the Output on screen.
var timer = 5;
var myinterval = setInterval(function () {
if (timer > 0) {
timer--;
document.write(timer+"<br>");
} else {
document.write("Time's Up");
clearInterval(myinterval);
}
}, 1000);