How to use clearInterval() in Angular 4

Kevin Shi picture Kevin Shi · Jul 25, 2017 · Viewed 22.1k times · Source

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?

Answer

Sajeetharan picture Sajeetharan · Jul 25, 2017

You can set like this,

  this.interval = setInterval(() => {

  }, 1000);

and clear like this,

if (this.interval) {
   clearInterval(this.interval);
}