简体   繁体   中英

I am using setTimeout() to call a refresh function, but it doesnt stop calling refresh when I move to another component?

I am new to angular, and I am having a function, refresh, which i need to call after every 1 min but when I am into that component it works fine and when i navigate to some other view it is still calling the refresh function, refresh function is called in ngOnInit() and then this setTimeout() function i have created in the refresh() function only.

ngOnInit(){
 this.refresh();
 }
 ...
 ...

refresh(){
...
...

setTimeout(() => {
  this.refresh();
   },10000) 
 }

You should use setInterval instead of setTimeout and in ngOnDestroy you need to use clearInterval

this.timer = setInterval(() => {
   this.refresh();
}, 10000);

Clear interval

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

You can create one more property like timeout and update your class like so,

ngOnInit(){
 this.refresh();
 }
 ...
 ...
timeout;
refresh(){
...
...

this.timeout = setTimeout(() => {
  this.refresh();
   },10000) 
 }
ngOnDestroy(){
  clearTimeout(this.timeout);
}

Your class will have to implement OnDestroy interface for this besides OnInit .

Although for your use case, setInterval makes more sense and also you can make a reusable service like IntervalService to encapsulate the whole behaviour.

The setInterval bit:-

interval;

ngOnInit()
{
this.interval = setInterval(() => {
   this.refresh();
}, 10000);
}
ngOnDestroy(){
  clearInterval(this.interval);
}

refresh(){....}

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