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 - Async Promise INPUT millis = 1000 1000 ms = 1 second async function sleep(millis) ALGORITHM STEPS 1 Create Promise Return new Promise object 2 Set Timeout setTimeout(resolve, millis) 3 Wait Duration JS event loop waits 1000ms 4 Resolve Promise Callback executes resolve() const sleep = (ms) => new Promise( (resolve) => setTimeout( resolve, ms) ); FINAL RESULT Timeline 0ms 1000ms OK Output: "Sleep completed" Promise State: FULFILLED Key Insight: The sleep function wraps setTimeout in a Promise, allowing async/await syntax. When setTimeout expires after 'millis' ms, it calls resolve(), which fulfills the Promise. TutorialsPoint - Sleep | Promise-based setTimeout Approach
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