TheUnreal
TheUnreal

Reputation: 24472

Angular 2 setinterval() keep running on other component

I have the following method in one component:

ngOnInit()
        {
            this.battleInit();
            setInterval(() => {
                this.battleInit(); 
                }, 5000);
        }

Now, I need to run this interval only if the user is in this specific component, that means that when the user navigate away from this component the interval will stop.

Currently, this.battleInit() is executed every 5 seconds, even after the user navigates away from this page.

Short question: How do I stop setInterval() when user navigate away (by routing) to another component?

Upvotes: 67

Views: 172638

Answers (2)

every 40 seconds

 polling: any;

  ngOnInit() {

    this.consulta();
    this.pollData();
  }

 pollData () {
    this.polling = setInterval(() => {
    this.consulta();

  },40*1000)

 ngOnDestroy() {
    clearInterval(this.polling);
  }

Upvotes: 8

Thierry Templier
Thierry Templier

Reputation: 202176

You need to use clearInterval method for this within the ngOnDestroy hook method of your component. For this you need to save the returned value by the setInterval method.

Here is a sample:

ngOnInit() {
  this.battleInit();
  this.id = setInterval(() => {
    this.battleInit(); 
  }, 5000);
}

ngOnDestroy() {
  if (this.id) {
    clearInterval(this.id);
  }
}

Upvotes: 186

Related Questions