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.
Example :
I call this on a method to start the 10 seconds API calls
setTimeout(() => {
this.onTimeOut();
}, 1000);
And this is the onTimeOut()
method...
onTimeOut() {
this.ApiCall().then(
success => {
if(success ['ok'] == 0){
this.navCtrl.push(myPage);
}
},
error => { console.log(error); });
}
setTimeout(() => {
this.onTimeOut();
}, 1000);
}
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.
The goal is when it joins the if and push the page, stop the timer.
Use
observable.timer
for your purpose in angular way.Better use observables
to stop it use
Make sure to import
interval
withThere is nothing wrong with setTiimeout, It’s just a bug in your codes. This is indeed an infinite loop(recursive function without a base condition) as you don't have any base condition there.
So, setTimeout will keep on calling onTimeOut() after every 1 second as it does not know where to stop. Just use a base condition to finish the recursion when you switch to other pages.
ngOnDestroy
method will set the flag as false and the last call of the recursive function won't go inside the if block and as there is nothing to be executed after that, It will return back (previous state of it) and will clear it up from the stack, This process will be repeated till the stack is cleared up(same thing would happen to previous version of it which is now on the top of the stack and thus will clear up the stack one by one recursively).A better solution than setTimeout in an Angular app could be to use Observable. Observable have a method named timer that you can use this way (and there is a TimerObservable too but I never used it so I don't know if this is the same thing):
I encourage you to use RxJS and Observable for your requests too, instead of promises, it seams more the Angular way to do things to me, and RxJS is a really powerful library.
RxJS Observable doc