Angular 2 setinterval() keep running on other component

Angular

Angular Problem Overview


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?

Angular Solutions


Solution 1 - Angular

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

Solution 2 - Angular

every 40 seconds

 polling: any;

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

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

  },40*1000)

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

Solution 3 - Angular

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

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

this.id is an identifier returned by the setInterval that can be used to cancel the operation using clearInterval.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTheUnrealView Question on Stackoverflow
Solution 1 - AngularThierry TemplierView Answer on Stackoverflow
Solution 2 - AngularDanna Luciana Carrillo PerezView Answer on Stackoverflow
Solution 3 - AngularArqam.RafayView Answer on Stackoverflow