Sleep Function
December 21, 2025
Need to pause execution in an async function? A sleep utility is a simple and powerful tool for delaying code.
export const sleep = (ms: number): Promise<void> =>
new Promise((resolve) => setTimeout(resolve, ms));
How It Works
- setTimeout(resolve, ms) schedules the resolve after ms milliseconds.
- Wrapped in a Promise, so you can await it inside async functions.
Example
async function run() {
console.log("Start");
await sleep(2000);
console.log("2 seconds later...");
}
run();
Output:
Start
(2-second delay)
2 seconds later...
Use Cases
- Throttling tasks in loops
- Simulating network delays in tests
- Waiting before retrying failed operations
Note
Don’t use sleep in synchronous code — it's async-only. Also, avoid excessive delays in production code unless it’s intentional and safe.
A tiny utility, but extremely useful in testing and async flows!