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}`);
});
Output:
Received value after delay: 1
Received value after delay: 2
Received value after delay: 3
Similar Reads
How to Create an Object in TypeScript?
TypeScript object is a collection of key-value pairs, where keys are strings and values can be any data type. Objects in TypeScript can store various types, including primitives, arrays, and functions, providing a structured way to organize and manipulate data.Creating Objects in TypescriptNow, let
4 min read
How to Create a Stack in TypeScript using an Array ?
Stack is a linear Data Structure that is based on the LIFO concept (last in first out). There are 5 primary operations in the stack as follows:push method(): This method adds element x to the stack.pop() Method: This method removes the last element of the stack.peek() Method: This method returns the
3 min read
How to use Async/Await with a Promise in TypeScript ?
In TypeScript, you can use async and await with a Promise to simplify asynchronous code and make it more readable.What is a Promise?A promise in TypeScript is an object representing the eventual completion or failure of an asynchronous operation. It acts as a placeholder for a value that may be avai
3 min read
How to Sort an Array in TypeScript ?
Array sorting is the process of arranging the elements within an array in a specified order, often either ascending or descending based on predetermined criteria. Below are the approaches used to sort an array in typescript: Table of Content Method 1: Using sort methodMethod 2: Spread OperatorMethod
3 min read
How to Create Deep Readonly Type in Typescript?
In TypeScript, the readonly access modifier is a powerful tool that ensures immutability by marking properties of a class as immutable. Once a property is markedreadonly, it cannot be reassigned. This is highly useful for maintaining consistent and safe data structures, especially in scenarios such
3 min read
How to use Async Await with Array.map in TypeScript ?
In this article, we will learn how we can use async wait with Array.map() method in TypeScript. In TypeScript, the async and await are mainly used to work with asynchronous tasks. Using this we can write the code that consists of the tasks that take time to complete like reading the file, fetching d
3 min read
How to Return an Empty Promise in TypeScript ?
In TypeScript, you can return an empty promise to create an empty asynchronous task. There are mainly two ways that can be used to create empty promises in TypeScript as listed below. Table of Content By using the Promise.resolve() methodBy immediately resolving the promiseUsing async/await to Retur
2 min read
How to Create an Interface with Condtional Type ?
Conditional types in TypeScript offer developers the ability to craft interfaces that adapt their behavior based on the types they encounter. This feature enhances code flexibility and adaptability, particularly in situations where types may vary. By employing conditional types, developers can defin
3 min read
How to write a function in Typescript ?
Writing a function in TypeScript is similar to writing it in JavaScript but with added parameters and return type. Note that any JavaScript function is a perfectly valid TypeScript function. However, we can do better by adding type.Syntax: Let's see a basic TypeScript function syntax (with two argum
4 min read
How to Declare a Fixed Length Array in TypeScript ?
To declare a Fixed-length Array in TypeScript you can use a Tuple. Tuple types allow you to specify the types for each element in the array and, importantly, define a fixed number of elements in a specific order. In this article, we are going to learn how to declare a fixed-length array in TypeScrip
3 min read