Call a function every 10 seconds Angular2
Better use observables
this.sub = Observable.interval(10000) .subscribe((val) => { console.log('called'); });
to stop it use
this.sub.unsubscribe();
Make sure to import interval
with
import 'rxjs/add/observable/interval';
from RxJS 6+ you just use interval.
import { interval } from 'rxjs';//in 10 seconds do somethinginterval(10000).subscribe(x => { this.myFunctionThatDoesStuff();});
you can use Subscription
with the interval.
import { interval, Subscription} from 'rxjs';export class intervalDemo{ mySubscription: Subscription constructor(){ this.mySubscription= interval(5000).subscribe((x =>{ this.doStuff(); })); } doStuff(){ //doing stuff with unsubscribe at end to only run once this.failedRequestSub.unsubscribe(); }}
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):
timer = Observable.timer(initialDelay, period);timer.subscribe(tick => { // Your API call, which will be performed every period});
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.