Delay execution in async functions with a sleep utility.
export const sleep = (ms: number): Promise<void> =>
new Promise((resolve) => setTimeout(resolve, ms));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));
async function run() {
console.log("Start");
await sleep(2000);
console.log("2 seconds later...");
}
run();
Output:
Start
(2-second delay)
2 seconds later...
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!