每 10 秒调用一个函数 Angular2 [英] Call a function every 10 seconds Angular2
问题描述
我正在尝试创建一个 Timer
,它每 10 秒调用一次 API 调用
,我正在使用 setTimeOut
但问题是它变成了一个无限循环,即使我推到另一个页面,它也会继续加入 if 条件.
I'm trying to create a Timer
that calls an API call
every 10 seconds, I'm using setTimeOut
but the thing is that it becomes an infinite loop, and even if I push to another page it keeps joining the if condition.
示例:
我在一个方法上调用它来启动 10 秒 API 调用
I call this on a method to start the 10 seconds API calls
setTimeout(() => {
this.onTimeOut();
}, 1000);
这是 onTimeOut()
方法...
onTimeOut() {
this.ApiCall().then(
success => {
if(success ['ok'] == 0){
this.navCtrl.push(myPage);
}
},
error => { console.log(error); });
}
setTimeout(() => {
this.onTimeOut();
}, 1000);
}
我听说过 Debounce
和 rxjs/rs
但我不熟悉它们,你能给我一些提示来做同样的事情吗?或者,如果这种方式更有效,请继续向我解释为什么它会变成循环.
I've heard about Debounce
and rxjs/rs
but I'm not familiar with them, could you give me some tips to do the same with that? Or if this way is more efficient go ahead and explain to me why it becomes to a loop.
目标是当它加入if并推送页面时,停止计时器.
The goal is when it joins the if and push the page, stop the timer.
推荐答案
更好地使用 observables
Better use observables
this.sub = Observable.interval(10000)
.subscribe((val) => { console.log('called'); });
停止使用
this.sub.unsubscribe();
确保使用
import 'rxjs/add/observable/interval';
这篇关于每 10 秒调用一个函数 Angular2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!