How to use clearInterval() in Angular 4
Asked Answered
V

3

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?

Verlaverlee answered 25/7, 2017 at 3:54 Comment(0)
T
37

You can set like this,

  this.interval = setInterval(() => {

  }, 1000);

and clear like this,

if (this.interval) {
   clearInterval(this.interval);
}
Trilemma answered 25/7, 2017 at 4:1 Comment(2)
This worked, thanks. Would you mind explaining why it works like this when clearing it inside the interval doesn't?Verlaverlee
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.Hypochondria
M
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);
Morissa answered 13/3, 2019 at 9:50 Comment(0)
A
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.

Alexandra answered 14/2, 2021 at 18:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.