avatar

Le Do Nghiem

Software Engineer

  • About me
  • Books
  • Snippets
  • Blog

© 2026 Le Do Nghiem. All rights reserved.

Contact |

Back to Snippets

Sleep Function

Delay execution in async functions with a sleep utility.

LanguageTypeScript
Last UpdatedDec 21, 2025
sleep.ts
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));

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!

Previous Snippet

useCopyToClipboard Hook

Next Snippet

generateId Function