63

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?

2 Answers 2

179

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);
  }
}
4
  • 1
    Thanks! What will console.log(this.id) return?
    – TheUnreal
    May 9, 2016 at 13:12
  • @ThierryTemplier: Can you pls solve my issue , stackoverflow.com/questions/52836512/…
    – Abhi
    Oct 17, 2018 at 2:15
  • If someone is using Ionic you can also change ngOnInit for ionViewDidLoad and ngOnDestroy for ionViewDidLeave.
    – Eloy Ruiz
    Jan 20, 2020 at 2:12
  • Great answer! Helped me, but a small update would to this would help. Include the declaration of this.id and its type. The type is NodeJS.Timeout. So this code: id = new NodeJS.Timeout()
    – David J
    Jan 8 at 13:24
7

every 40 seconds

 polling: any;

  ngOnInit() {

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

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

  },40*1000)

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.