delay
delay shifts each value emitted by the source observable forward in time, either by a fixed duration in milliseconds or until a specific Date. When the argument is a number, the operator postpones every emission by that many milliseconds. When a date is supplied, incoming values are buffered and then released starting at that moment, with the original spacing between them maintained.
Importantly, delay keeps the relative time gaps between values intact. If the source produces three items back-to-back, all three will be held back by the delay period but will still arrive in quick succession, with intervals equal (or nearly equal) to the those of the original emissions. This behavior differs from the interval operator, which inserts delays between individual values.
The operator’s mechanics are as follows:
- It subscribes to the source observable.
- Each new value is stored in an internal buffer, and a timer is started for that specific value.
- When the timer completes, the corresponding value is forwarded to the observer.
- A complete notification is sent to the observer once the source finishes.
- An error notification is delivered if the source throws an error.
By default, the operator relies on setInterval via AsyncScheduler for its internal scheduling.
Usage
A frequent use case for delay is emulating asynchronous operations, such as network calls.
Below is an example that shows how to mimic network latency across three requests:
const 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)
);
}
