Reputation: 103
I have a condition here which is if a = 6
, stop the setInterval
so I used clearInterval
for my condition, but it doesn't take effect, anybody can help me how I can make the clearInterval
work under that condition?
Please take note that in my case makig doSomething
to execute after some amount of time is of paramount importance as well, that's why I used setTimeout
here.
function doSomething() {
let a = 1;
return setInterval(() => {
if (a < 6) {
a++;
console.log(a);
} else {
a = 1;
}
}, 1000)
}
setTimeout(doSomething, 5000);
var id = doSomething();
if (a === 6) {
clearInterval(id);
}
Upvotes: 0
Views: 72
Reputation: 5941
You can call clearInterval
inside the setInterval
- I think this is what you're trying to achieve:
let intervalId;
function doSomething() {
let a = 1;
return setInterval(() => {
console.log(a);
if (a++ === 6) {
clearInterval(intervalId);
}
}, 1000);
}
setTimeout(() => {
intervalId = doSomething();
}, 5000);
console.log('Waiting for 5 seconds before calling doSomething..');
Upvotes: 1