Call a function every x seconds in Angular

Updated:

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.

Example

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 
      }) 
    ).subscribe(); 
} 
     
// don't forget to unsubscribe when the Observable is not necessary anymore 
ngOnDestroy(): void { 
  this.timerSubscription.unsubscribe(); 
} 

Other methods

You have multiple other methods to call regularly a method / external service.

interval

rxjs provides the interval operator. Here you find the interval documentation.

The main difference between interval and timer is that interval emits the first time after the first period has passed (in our example 10 seconds).

timer can wait a specified amount of time before to emit the first time.

import { Observable, Subscription, interval } from 'rxjs'; 
import { switchMap } from 'rxjs/operators'; 
 
... 
 
yourSubscription: Subscription; 
 
ngOnInit() { 
    this.dataSubscription = interval(10000) // Repeat every 10 seconds 
        .pipe( 
            switchMap(() => this.getData()) // Switch to new observable on every interval 
        ) 
        .subscribe(data => { 
            // Do something with the data here 
        }); 
} 
 
ngOnDestroy() { 
    this.yourSubscription.unsubscribe(); // Unsubscribe when the component is destroyed 
} 

In this example, the interval operator emits a value every 10 seconds, which triggers the switchMap operator to switch to the new observable returned by getData().

setInterval - Javascript

If you want to avoid rxjs you can use a more native api: setInterval. setInterval works directly in Javascript without the need of any additional framework.
You can find the documentation and some examples on mozilla.org.

async - await

If you are not afraid to use Promises you can implement the same solution with await and asyc.

Here an example:

data: any; 
 
async ngOnInit() { 
  while (true) { 
    this.data = await this.getData().toPromise(); 
    // Do something with the data here 
    await this.delay(10000); 
  } 
} 
 
delay(milliseconds: number) { 
  return new Promise(resolve => setTimeout(resolve, milliseconds)); 
} 

WebApp built by Marco using SpringBoot 3.2.4 and Java 21, in a Server in Switzerland