How to Create an Observable with a Delay in TypeScript ?
Last Updated :
24 Apr, 2025
Creating observables with delays is a common requirement in TypeScript applications, especially when dealing with asynchronous operations. To achieve this, we leverage the power of the rxjs
library.
What is rxjs library?
The RxJS library is a powerful reactive programming library for JavaScript and TypeScript. It provides a set of tools for working with asynchronous data streams, allowing developers to easily manage and manipulate sequences of events or values over time.
In TypeScript, you can use RxJS to create observables, which are sequences that can emit multiple values over time. To incorporate a delay into your observables, RxJS provides the delay
operator. This operator allows you to introduce a time delay before emitting each value in the observable stream.
Follow the below steps to create an observable with a delay in TypeScript:
Step 1: Make sure you have the RxJS library installed in your TypeScript project. You can install it using npm.
npm install rxjs
Step 2: Import Required Modules
Import the necessary modules from RxJS in your TypeScript file:
import { Observable, of } from 'rxjs';
import { delay } from 'rxjs/operators';
Step 3: Create an Observable
Use the of
function to create an observable with the values you want. For example, an observable with the values 1, 2, and 3.
const myObservable: Observable<number> = of(1, 2, 3);
Step 4: Apply the Delay Operator
Use the delay
operator to introduce a delay before emitting each value. For instance, a delay of 1000 milliseconds (1 second).
const delayedObservable: Observable<number> = myObservable.pipe(delay(1000));
Step 5: Subscribe to the Observable
Subscribe to the delayed observable to receive the values after the specified delay:
delayedObservable.subscribe(value => {
console.log(`Received value after delay: ${value}`);
});
Feel free to adjust the values in the observable and the duration of the delay according to your specific use case.
Example: In this example,, we create an observable with a 1-second delay between emitted values. We import Observable
and the delay
operator, then define myObservable
with values 1, 2, and 3. Applying the delay
operator creates delayedObservable
. Subscribing to it, we log each emitted value after a 1-second delay using a console.log
statement.
JavaScript
// Step 1: Import required modules from RxJS
import { Observable, of } from 'rxjs';
import { delay } from 'rxjs/operators';
// Step 2: Create an observable with values 1, 2, and 3
const myObservable: Observable<number> = of(1, 2, 3);
// Step 3: Apply the delay operator to
// introduce a delay of 1000 milliseconds (1 second)
const delayedObservable: Observable<number> =
myObservable.pipe(delay(1000));
// Step 4: Subscribe to the delayed observable
delayedObservable.subscribe(value => {
// Step 5: Execute logic when each
// value is emitted after the delay
console.log(`Received value after delay: ${value}`);
});