Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    })
 }
like image 460
SUBHASIS MONDAL Avatar asked Dec 23 '17 09:12

SUBHASIS MONDAL


2 Answers

You forgot to return the instance of the interval.

interval(){
  return setInterval(()=>{
    this.getData();
  },20000)
}
like image 138
zgue Avatar answered Sep 18 '22 15:09

zgue


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)
}
like image 34
Patryk Brejdak Avatar answered Sep 16 '22 15:09

Patryk Brejdak