In the asynchronous world of modern JavaScript, there are times when we want to pause execution—whether it's to simulate latency, manage API rate limits, or add subtle timing in UI transitions.
But unlike some other languages, JavaScript doesn’t come with a built-in sleep() function. So how do we wait without blocking the main thread?
Introducing the delay() Function
JavaScript developers commonly create a reusable utility using Promises and setTimeout():
jsCopyEdit
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
ms defines the duration to pause in milliseconds.
setTimeout(resolve, ms) waits for the time and then resolves the Promise.
Once resolved, the rest of the async function can continue executing.
You can use delay() in two ways:
Using .then()
jsCopyEdit
delay(1000).then(() => { console.log("Executed after 1 second"); });
With async/await
jsCopyEdit
const run = async () => { console.log("Start"); await delay(2000); console.log("After 2 seconds"); }; run();
This makes the delay feel more natural within asynchronous logic, without freezing the UI or blocking event loops.
Controlled Timing in Async Workflows
Add intentional gaps between API calls or animations.
Retry Failed Requests
Implement retry logic with a delay between attempts.
API Rate Limiting
Prevent hitting limits by spacing out network calls.
delay() works only in asynchronous code — you must use await or .then().
It’s non-blocking, meaning the rest of the JavaScript thread stays responsive.
Avoid heavy use in loops unless properly optimized — delays can slow down performance if misused.
Though it’s just a few lines of code, delay() is a powerful utility for modern developers. It offers elegant timing control in asynchronous scenarios and contributes to writing more maintainable, readable code.
Whether you’re managing retries, creating animation gaps, or just simulating latency, adding delay() to your toolbox can truly elevate your JavaScript code.
Want more practical JS tricks like this? Stay tuned for upcoming posts or share your favorite use case for delay() in the comments!