Sometimes, you need to pause execution in JavaScript, like waiting for an API response or adding a delay between actions. Here’s how you can implement a delay
(or sleep
) function using modern JavaScript.
Using Promises
The setTimeout
function is great for delays. Combine it with promises to create a reusable delay function:
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
This function resolves the promise after the specified time in milliseconds (ms
).
Using Async/Await
With async/await
, you can make the delay work like a synchronous pause inside asynchronous functions:
async function example() {
console.log('Start');
await delay(2000); // Pause for 2 seconds
console.log('End');
}
example();
Key Points:
-
delay(ms)
returns a promise that resolves afterms
milliseconds. -
await
pauses execution in anasync
function until the promise resolves.
Why Use This Method?
It’s clean, modern, and avoids callback hell. Perfect for developers looking to write readable asynchronous code.
Got questions? Drop them below!
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.