问题
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?
回答1:
You can set like this,
this.interval = setInterval(() => {
}, 1000);
and clear like this,
if (this.interval) {
clearInterval(this.interval);
}
回答2:
If you want in same method with some condition
var a = 1;
this.interval = setInterval(() => {
console.log(a++)
if(a > 30){
clearInterval(this.interval);
}
}, 1000);
来源:https://stackoverflow.com/questions/45293635/how-to-use-clearinterval-in-angular-4