How to use clearInterval() in Angular 4

落花浮王杯 提交于 2020-06-24 08:38:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!