Back to blog
Feb 12, 2025
4 min read

Sleep

Implement an async sleep function that delays execution for a specified number of milliseconds.

Difficulty: Easy | Acceptance: 87.40% | Paid: No Topics: N/A

Write a function that sleeps for a given number of milliseconds.

Examples

Example 1

Input: millis = 100
Output: 100
Explanation: It should return a promise that resolves after 100ms. 
let t = Date.now(); 
sleep(100).then(() => console.log(Date.now() - t)); // 100

Example 2

Input: millis = 200
Output: 200
Explanation: It should return a promise that resolves after 200ms.

Constraints

1 <= millis <= 1000

Approach 1: Promise with setTimeout

Intuition Use the Promise constructor with setTimeout to create a delay that resolves after the specified time.

Steps

  • Create a new Promise
  • Use setTimeout to resolve the promise after millis milliseconds
  • Return the promise
python
import asyncio

async def sleep(millis: int) -> None:
    await asyncio.sleep(millis / 1000)

Complexity

  • Time: O(millis) where millis is the sleep time
  • Space: O(1)
  • Notes: This is the standard way to implement sleep in JavaScript/TypeScript

Approach 2: Async/Await Pattern

Intuition Use async/await syntax to wait for the Promise to resolve before continuing.

Steps

  • Define an async function
  • Create a Promise with setTimeout
  • Await the Promise to ensure the delay
  • Return nothing (void)
python
import asyncio

async def sleep(millis: int) -> None:
    await asyncio.sleep(millis / 1000)

Complexity

  • Time: O(millis) where millis is the sleep time
  • Space: O(1)
  • Notes: Using await makes the code more readable when used in async contexts

Approach 3: Direct Promise Return

Intuition Return a Promise directly without using the async keyword for a more explicit return type.

Steps

  • Define a function that returns Promise<void>
  • Create a new Promise with setTimeout
  • Return the promise directly
python
import asyncio

async def sleep(millis: int) -> None:
    await asyncio.sleep(millis / 1000)

Complexity

  • Time: O(millis) where millis is the sleep time
  • Space: O(1)
  • Notes: This approach explicitly shows the Promise return type without async sugar