RxJS Operators – delay

RxJS operators - delay

The delay operator in RxJS delays the emitted value by specified time.

Consider the following example. The name$ observable will produce output almost instantaneously without any delay.

const name$ = of('Harshal');
name$.subscribe(name => console.log(name));

To add a delay to the above observable we need to first import the delay operator.

import { delay } from 'rxjs/operators';

Next we need to add pipe to Observable to consume the delay operator.

const name$ = of('Harshal').pipe(delay(4000));
name$.subscribe(name => console.log(name));

This will add a delay of 4000 milliseconds i.e 4 seconds to the name$ observable.

You can also pass Date to delay operator.

const date = new Date('Dec 31 2050 23:59:59')
const message$ = of('Happy New Year!').pipe(delay(date));
message$.subscribe(name => console.log(name));

In the above example, the value within the message$ observable will be emitted only after the specified date.

One thought on “RxJS Operators – delay”

Leave a Reply

Your email address will not be published. Required fields are marked *