delay
delay
time shifts each emitted value from the source observable by a defined time span or until a given date. If the delay argument is a Number, this operator time shifts the source observable by that amount of time expressed in milliseconds. If the delay argument is a Date, delay
starts emitting all incoming values until that point at the date specified preserving the intervals between the values.
Note that delay
preserves the relative time intervals between the values. It means that if the source observable emits 3 items synchronously, all 3 of them will be delayed by a certain amount of time but delivered synchronously with a minimum time span between them. The time span will be equal or very close to the time span between the values emitted by the source obsevable. This is in contrast to how interval
operator works, which inserts delays in between the values.
delay
operator works in the following way:
- Subscribe to a source observable
- When a new value arrives from a source observable, add the value to internal cache and start a delay interval for that value
- Once the interval elapses, send the corresponding value to the observer
- Once the source observable completes, send the complete notification to the observer
- If the source observable throws an error, send the error notification to the observer
The following diagram demonstrates this sequence of steps:
By default the operator uses setInterval through AsyncScheduler under the hood for scheduling.
UsageLink to this section
delay
is commonly used to mock some asynchronous activity, such as network requests.
Here’s an example that demonstrates how to simulate network latency with 3 requests:
<>Copyconst api = 'https://reqres.in/api/users/'; const urls = [1, 2, 3].map(id => api + id); from(urls).pipe( mergeMap(url => mockHTTPRequest(url)) ).subscribe(val => console.log(val)); function mockHTTPRequest(url) { return of(`Response from ${url}`).pipe( // responses come in a random order delay(Math.random() * 1000) );