Call a function every 10 seconds Angular2

后端 未结 5 2088
臣服心动
臣服心动 2020-12-05 07:18

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 infin

5条回答
  •  独厮守ぢ
    2020-12-05 07:51

    from RxJS 6+ you just use interval.

    import { interval } from 'rxjs';
    
    //in 10 seconds do something
    interval(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();
        }
    }
    

提交回复
热议问题