Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use clearInterval() in Angular 4

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?

like image 226
Kevin Shi Avatar asked Jul 25 '17 03:07

Kevin Shi


People also ask

What is clearInterval?

The clearInterval() method clears a timer set with the setInterval() method.

Can you clearInterval within setInterval?

Calling clearInterval() inside setInterval() has no effect But after calling clearInterval(), it will continue to execute.

Does clearInterval stop?

I did make a fiddle to test it, and it turns out clearInterval stops all future execution, even those that have already be queued.

How do you break into setInterval?

If you set the return value of setInterval to a variable, you can use clearInterval to stop it.


1 Answers

You can set like this,

  this.interval = setInterval(() => {

  }, 1000);

and clear like this,

if (this.interval) {
   clearInterval(this.interval);
}
like image 63
Sajeetharan Avatar answered Sep 16 '22 16:09

Sajeetharan