Sleep - Problem

Given a positive integer millis, write an asynchronous function that sleeps for millis milliseconds. The function can resolve to any value.

Note: Minor deviation from millis in the actual sleep duration is acceptable.

Input & Output

Example 1 — Basic Sleep
$ Input: millis = 1000
Output: "Sleep completed"
💡 Note: Function sleeps for 1000 milliseconds (1 second) and then resolves with a value
Example 2 — Short Sleep
$ Input: millis = 100
Output: "Sleep completed"
💡 Note: Function sleeps for 100 milliseconds and resolves quickly
Example 3 — Minimal Sleep
$ Input: millis = 1
Output: "Sleep completed"
💡 Note: Function sleeps for just 1 millisecond, the minimum valid input

Constraints

  • 1 ≤ millis ≤ 1000

Visualization

Tap to expand
Sleep Function: Create Asynchronous DelayInputmillis1000Sleep Function Processingnew Promise((resolve) =>setTimeout(resolve, 1000))OutputPromiseResolves after delay⏰ Timer waits 1000ms → Promise resolves → Function completes✅ Async function that can be awaited
Understanding the Visualization
1
Input
Positive integer millis (e.g., 1000)
2
Process
Create async function that waits for millis milliseconds
3
Output
Promise that resolves after the delay
Key Takeaway
🎯 Key Insight: Wrap setTimeout in a Promise to create awaitable sleep functions
Asked in
Google 25 Microsoft 20 Facebook 15 Amazon 18
12.0K Views
Medium Frequency
~10 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen