This operator is your go-to when simulating real-world scenarios such as network latency or introducing a pause before a value is emitted. The delay
operator allows you to hold back values for a specified duration before they're released to subscribers.
Keep in mind that delay
won’t prevent the original observable from emitting values. It merely postpones the delivery to its subscribers. This is a gotcha as it could look like your data is lagging or not in sync with the source, especially when multiple observables are at play.
( StackBlitz )
import { fromEvent, of } from 'rxjs';
import { mergeMap, delay, takeUntil } from 'rxjs/operators';
const mousedown$ = fromEvent(document, 'mousedown');
const mouseup$ = fromEvent(document, 'mouseup');
mousedown$
.pipe(mergeMap(event => of(event).pipe(delay(700), takeUntil(mouseup$))))
.subscribe(event => console.log('Long Press!', event));
( StackBlitz )
// RxJS v6+
import { of, merge } from 'rxjs';
import { mapTo, delay } from 'rxjs/operators';
//emit one item
const example = of(null);
//delay output of each by an extra second
const message = merge(
example.pipe(mapTo('Hello')),
example.pipe(mapTo('World!'), delay(1000)),
example.pipe(mapTo('Goodbye'), delay(2000)),
example.pipe(mapTo('World!'), delay(3000))
);
//output: 'Hello'...'World!'...'Goodbye'...'World!'
const subscribe = message.subscribe(val => console.log(val));
- delay 📰 - Official docs
- delay - In Depth Dev Reference
- Transformation operator: delay and delayWhen 🎥 💵 - André Staltz
📁 Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/delay.ts