Angular 2 setinterval() keep running on other comp

2020-02-20 06:54发布

问题:

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?

回答1:

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


回答2:

below code are write <br> 
ngOnInit() {
  this.battleInit();
  this.id = setInterval(() => {
    this.battleInit(); 
  }, 5000);
}

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

this.id means number of iteration it triggered



回答3:

every 40 seconds

 polling: any;

  ngOnInit() {

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

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

  },40*1000)

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


标签: angular