[英]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.我是 angular 的新手,我有一个 function,刷新,我需要在每 1 分钟后调用一次,但是当我进入该组件时它工作正常,当我导航到其他视图时,它仍在调用刷新 ZC1C125268D18A94, refresh function 在 ngOnInit() 中调用,然后这个 setTimeout() function 我只在 refresh() function 中创建。
ngOnInit(){
this.refresh();
}
...
...
refresh(){
...
...
setTimeout(() => {
this.refresh();
},10000)
}
You should use setInterval
instead of setTimeout
and in ngOnDestroy you need to use clearInterval
您应该使用
setInterval
而不是setTimeout
并且在 ngOnDestroy 中您需要使用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,您可以再创建一个属性,例如
timeout
并像这样更新您的 class,
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
.除了
OnInit
之外,您的 class 还必须为此实现OnDestroy
接口。
Although for your use case, setInterval
makes more sense and also you can make a reusable service like IntervalService
to encapsulate the whole behaviour.尽管对于您的用例,
setInterval
更有意义,您也可以制作像IntervalService
这样的可重用服务来封装整个行为。
The setInterval bit:- setInterval 位:-
interval;
ngOnInit()
{
this.interval = setInterval(() => {
this.refresh();
}, 10000);
}
ngOnDestroy(){
clearInterval(this.interval);
}
refresh(){....}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.