SUBHASIS MONDAL
SUBHASIS MONDAL

Reputation: 723

clearinterval not working inside ngOnDestroy()

My ngOndestroy is calling with other route navigation but it is not executing clearInterval inside the method. Where am I making it wrong? It is running in background while i am in other component.

timer:any;

ngOnInit() {
  this.timer= this.interval();
};

 ngOnDestroy(){
    clearInterval(this.timer);
   console.log("Inside Destroy");


 }

interval(){
  setInterval(()=>{
    this.getData();
  },20000)
}
 getData(){
   this.dataservice.getdata()
      .subscribe(users=>{
      this.datas=users;
      console.log(this.datas);
    })
 }

Upvotes: 11

Views: 4695

Answers (2)

zgue
zgue

Reputation: 3850

You forgot to return the instance of the interval.

interval(){
  return setInterval(()=>{
    this.getData();
  },20000)
}

Upvotes: 9

Patryk Brejdak
Patryk Brejdak

Reputation: 1601

Because you are not returning any value to timer.

// you need to return interval identificator to be able to clear it later.
interval(){
  return setInterval(()=>{
    this.getData();
  },20000)
}

Upvotes: 2

Related Questions