CodeSphere
CodeSphere

Reputation: 1

Unable to stop setInterval() in angular

I am using setInterval() in angular to refresh my page but the refreshing of the page does not stop. I have used clearInterval() as well but it does not seems to work. Please guide and let me know if there is something wrong with the code or is there any other to stop the refreshing.

I used clearInterval() in the ngOnDistroy because it was affecting other components as well. But it also didn't worked.

AppComponent.ts

import { Component } from '@angular/core';
export class AppComponent {
  intervalId;
  i:number=0;
  n:number=0;

  ngOninit(){

  }

  refresh(){
    this.n++;
    alert("**** this is refresh method with "+this.n+" times.****");
    this.intervalId=setInterval(()=>{
      this.i++;
      if(this.i>3){
        console.log("we are in stop method");
        this.stopRefresh();
      }
      this.refresh();
    },60000);
  }

  stopRefresh(){
  clearInterval(this.intervalId);}


}

AppComponent.html

<div class="row">
    <div class="col-xs-12">
      <div>
        <button (click)="refresh()">Test</button>
      </div>
    </div>
</div>

I expected the code to stop after the value of variable 'i' reaches 3 but it keeps on going on and never stops.

Upvotes: 0

Views: 2480

Answers (2)

yanky_cranky
yanky_cranky

Reputation: 1363

The problem with your code is, you are calling "setInterval" inside recursive function "refresh" , hence this will create a new instance of "setInterval" everytime it encounters it.

To fix this, you can segregate your setInterval Logic into a new method and call that inside setInterval. Following code will fix it.

  refresh(){
    this.n++;
     console.log("we are in start method");
   // alert("**** this is refresh method with "+this.n+" times.****");

    this.intervalId=setInterval(()=>{

     this.myIntervalCode();
     // this.refresh();
    },3000);
  }

  myIntervalCode(){  
     this.i++;
      console.log("we are in start method");
      if(this.i>3){
        console.log("we are in stop method");
        this.stopRefresh();
      }
  }

  stopRefresh(){
  clearInterval(this.intervalId);
  }

enter image description here

Upvotes: 3

Andrei
Andrei

Reputation: 12001

setIterval(callback, 60000) makes callback invoke every 60_000 milliseconds. your code calls this.refresh(); inside of this interval, which spawns one more schedule for your refreshes. So it will be called 1 time in 60 seconds, 2 times in 120, 4 times in 180 etc. erase that line and everything should be better

Upvotes: 0

Related Questions