简体   繁体   中英

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?

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

every 40 seconds

 polling: any;

  ngOnInit() {

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

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

  },40*1000)

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

 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM