I recently answered a StackOverflow question where the user was asking for an alternative to setTimeout(). The question was a bit weirdly worded, and it turned out that the use of setTimeout() was an actual red herring to solve his actual problem.

But, I decided to write this blog post to explore an alternative to setTimeout() using RXJS, which is used heavily in Angular applications. RXJS is an Observable library, and Observables allow a lot of pipes to modify the results of the observable.

The pipe we care about is delay(), which adds an artificial delay in processing things.

First, create an Observable:

view plain print about
1const o = of([]);

We are using of() to create an Observable that immediately resolves. It is important to remember that observables do not execute until they are subscribed to.

Before we subscribe we can pipe the results. A pipe is just a way to process the results before sending them back to the subscriber. Let's pipe a delay:

view plain print about
1const o2 = o.pipe(
2 delay(6000)
3)

This pipes off the first observable, and saves it into a second. The pipe delays the return of the value for 6 seconds.

Now, subscribe and do something:

o2.subscribe((results) => { // do something console.log('something'); });

This is all fine and dandy, but lets take some time stamps to make sure the code actually works:

view plain print about
1const o = of([]);
2 const 02 = o.pipe(
3 delay(6000)
4 );
5 const startTime = new Date().getTime();
6 o2.subscribe((result: any[]) =>
{
7 const endTime = new Date().getTime();
8 console.log('start time ', startTime);
9 console.log('end time ', endTime );
10 console.log('difference ', endTime - startTime);
11 });

The getTime() function of the Date Class is used to get the time before we start processing, and time after we finish processing.

Run this code inside the constructor of a class or component, and you should see something like this in the console:

The values are not exactly 6 seconds because other processing takes place, but it is pretty close.

You can play around with the code over here