Why doesn't stopInterval clear mave? mave keeps logging 'g' even after calling stopInterval().
let boy = 'bama';
let count = 1;
const name = () => {
let stopInterval = () => {
if (count >= 1) {
clearInterval(mave);
}
}
if (boy === 'lama') {
stopInterval();
var move = setInterval(() => {
console.log('u');
},3000);
} else if (boy === 'bama') {
stopInterval();
var mave = setInterval(() => {
console.log('g');
},3000);
}
};
name();
setInterval when invokes will return a timerId, You have to clear that Id.
You are not clearing the id on every time the interval runs, you can call the function stopInterval on every run of callback that you have passed to setInterval
let boy = "bama";
let count = 1;
const name = () => {
let id; //change - create id variable on top of function
let stopInterval = () => {
if (count >= 1) {
clearInterval(id);
}
};
if (boy === "lama") {
id = setInterval(() => { //change - Assigning ID
stopInterval(); //change - Run every time and check
console.log("u");
}, 3000);
} else if (boy === "bama") {
id = setInterval(() => { //change - Assigning ID
stopInterval(); //change - Run every time and check
console.log("g");
}, 3000);
}
};
name();
Alternate short solution
let boy = "bama";
let count = 1;
const name = () => {
var timerId = setInterval(() => {
if (count++ >= 3) clearInterval(timerId);
if (boy === "lama") console.log("u");
else console.log("g");
}, 3000);
};
name();
You don't provide any condition to stop/ clear that intervall. Right from the start, the first thing you is to stop the intervall (which hasn't started already). Then you start the intervall and do not provide anything to stop that. set the stopIntervall command where you console.log("g") and when debugging you see the difference.
It would seem something is missing from this program, the only the he interval is set is
var mave = setInterval(()//etc
Which sets "mave" as a local variable which is only visible in the scope of that if statement, and after that happens the is no "stopInterval", you are only calling it before you start it
First, you need to either make mave a global variable, or simply pass it as a parameter to stopInterval (but then it would be the same a clear, so might as well just use that) but mainly, you actually have to stop it AFTER you start it
Try just making a button that clears it when clicked, or anything