I want to stop interval after it reaches 0, but it goes on and on...
here is my code
function timer() {
var health = 100;
var counter = 0;
if (health > 0) {
counter = setInterval(function () {
reduce = Math.floor(Math.random() * 15);
health = health - reduce;
console.log(health);
}, 1000);
} else {
clearInterval(counter);
}
}
Do the check and conditional clearInterval inside the scheduled function:
function timer() {
var health = 100;
var counter = setInterval(function () {
var reduce = Math.floor(Math.random() * 15);
health = health - reduce;
console.log(health);
if (health < 0) {
clearInterval(counter);
}
}, 1000);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With