I am trying to use setInterval in my Angular 4 app.
const inter = setInterval(() => {
// logic resulting in exitCondition
if(exitCondition) {
clearInterval(inter);
}
}, 1000);
This set up works fine in vanilla javascript, but clearInterval()
does not seem to work in Angular. Upon doing some research I found an interval service for Angular 1.x :
https://docs.angularjs.org/api/ng/service/$interval
Is there anything similar for Angular 4? Or is there a workaround to make clearInterval() work?
The clearInterval() method clears a timer set with the setInterval() method.
Calling clearInterval() inside setInterval() has no effect But after calling clearInterval(), it will continue to execute.
I did make a fiddle to test it, and it turns out clearInterval stops all future execution, even those that have already be queued.
If you set the return value of setInterval to a variable, you can use clearInterval to stop it.
You can set like this,
this.interval = setInterval(() => {
}, 1000);
and clear like this,
if (this.interval) {
clearInterval(this.interval);
}
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