15

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?

Kevin Shi
  • 496
  • 1
  • 7
  • 18

3 Answers3

38

You can set like this,

  this.interval = setInterval(() => {

  }, 1000);

and clear like this,

if (this.interval) {
   clearInterval(this.interval);
}
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • This worked, thanks. Would you mind explaining why it works like this when clearing it inside the interval doesn't? – Kevin Shi Jul 25 '17 at 04:30
  • because `this` doesn't refer to your original object in your callback when you invoke it that way. -- if you want `this` to work, you can declare your function as a lambda, like this: `private callback = () => { clearInterval(this.interval); };` -- you can call it from anywhere in your class just like a regular method (even make it public), and then `this` will work correctly. – BrainSlugs83 Mar 20 '20 at 23:47
1

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);
Ashutosh Jha
  • 15,451
  • 11
  • 52
  • 85
0

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.

Furkan Gulsen
  • 1,384
  • 2
  • 12
  • 24