You’re probably familiar with setTimeout
(to run some code after a given timeout) and setInterval
(to run some code at a given time interval). Both are “native” Javascript functions and can be used with Angular.
That said, recurring code execution is asynchronous, and asynchronous work is often done with RxJs in Angular apps. As a result, let’s talk about a 100% RxJs way to replace setTimeout
and setInterval
.
The RxJS timer
operator creates an observable that emits a value after a specified delay. The delay can be specified in milliseconds or as a Date
object.
The following code creates an observable that emits a value (0) after one second:
If we want timer
to emit immediately and then keep emitting at a given interval, we can do the following:
This would emit 0 immediately, then 1 five seconds later, 2 ten seconds later, etc. Most of the time, we don’t care about the emitted number. We want to turn that Observable into another one (like an HTTP request, for instance) using our good friend switchMap
:
What’s the benefit of using timer
in such scenarios? We get automatic unsubscriptions if we use the async
pipe or the takeUntilDestroyed
operator.
Here is a tutorial for a concrete example of how to do HTTP polling with Angular and the timer
operator.