How to use clearInterval() in Angular 4

Viewed 29529

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?

3 Answers

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);

If the setInterval function starts after the user presses the key, there is a problem. If the user presses the key more than once, the following happens:

  • setInterval1 -> start
  • setInterval2 -> start

And when the stop button is pressed:

  • setInterval2 -> stop

For this reason, the setInterval1 process never stops. For this, we need to declare a boolean value variable. It will get the value "true" when the key is pressed and check it with "if" at the beginning of the function.

Related