Call a function every x seconds in Angular

This is a quick solution to retrieve the results every x seconds or minutes.

It creates a subscription to a RxJS function timer. This function creates an Observable that emit a result after a certain time.


To call the http request every 10 seconds:

import {Subscription, timer} from 'rxjs';  
timerSubscription: Subscription; 
 ngOnInit(): void { 
      // timer(0, 10000) call the function immediately and every 10 seconds 
      this.timerSubscription = timer(0, 10000).pipe( 
      map(() => { 
        this.loadData(); // load data contains the http request 
// don't forget to unsubscribe when the Observable is not necessary anymore 
ngOnDestroy(): void { 

WebApp built by Marco using SpringBoot, Java 16, Mustache, Markdown and Hosted using Jelastic