In modern JavaScript development, especially in asynchronous programming, it's often necessary to pause code execution for a specified duration.

While JavaScript doesn't natively support a sleep function like some other languages, we can simulate this behavior using Promises and setTimeout(). One common utility function used to achieve this is the delay function:
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));The delay function is a simple utility that returns a Promise. Here's a breakdown:
ms is the number of milliseconds to wait.
setTimeout(resolve, ms) calls the resolve function after the specified delay.
The returned Promise will only resolve after ms milliseconds, allowing you to await it in an async function.
In essence, delay(ms) lets your code "pause" for a specified time without blocking the entire JavaScript thread, thanks to the asynchronous nature of Promises.
delay(1000).then(() => {
console.log("Executed after 1 second");
});or by using async / await
const run = async () => {
console.log("Start");
await delay(2000);
console.log("After 2 seconds");
};
run();1. Adding a Pause in Async Code: Sometimes you need to wait before making another API request or to simulate network latency:
2. Retry Mechanism: You can use delay to wait before retrying a failed request:
3. Rate LimitingAPIs often have rate limits. Using delay, you can space out requests to stay within the safe bounds.
delay only works in async functions (or inside .then() chains).
It doesn’t block the main thread like while loops or sync delays might.
Be careful using too many delays in loops—they can lead to performance issues or slow user experience if not managed well.
The delay function is a tiny but powerful helper in JavaScript. By combining setTimeout with Promises, it allows developers to elegantly handle pauses and timing in asynchronous code. Whether you're building APIs, animations, or retry logic, delay offers a clean and readable way to introduce time-based control.
In a world of increasingly asynchronous code, this small utility can make a big difference in writing clean, maintainable, and user-friendly applications.
#javascript #priyangsubanerjee
0
19
1