Sleep - Problem
Asynchronous Sleep Function

In JavaScript, sometimes you need to pause execution for a specific amount of time before continuing. Your task is to implement an asynchronous sleep function that waits for a given number of milliseconds before resolving.

Goal: Create a function that accepts a positive integer millis representing milliseconds, and returns a Promise that resolves after approximately that duration.

Input: A positive integer millis (milliseconds to sleep)
Output: A Promise that resolves after millis milliseconds (can resolve with any value)

Note: Minor deviations from the exact millisecond timing are acceptable due to JavaScript's event loop nature.

Input & Output

example_1.js โ€” Basic Sleep
$ Input: 100
โ€บ Output: Promise resolves after ~100ms
๐Ÿ’ก Note: The function creates a Promise that resolves after approximately 100 milliseconds using setTimeout
example_2.js โ€” Longer Sleep
$ Input: 1000
โ€บ Output: Promise resolves after ~1000ms (1 second)
๐Ÿ’ก Note: Demonstrates sleeping for 1 second (1000 milliseconds) - useful for delays between operations
example_3.js โ€” Short Sleep
$ Input: 1
โ€บ Output: Promise resolves after ~1ms
๐Ÿ’ก Note: Even very short delays work, though actual timing may be slightly longer due to JavaScript's event loop minimum delay

Constraints

  • 1 โ‰ค millis โ‰ค 1000
  • The function should return a Promise
  • Minor timing deviations are acceptable
  • The solution should be non-blocking

Visualization

Tap to expand
Asynchronous Sleep Function FlowNon-blocking Promise-based delay1CreatePromise2setTimeoutTimer3ReturnPromiseMain Thread FREEOther operations can executeTimer in Event LoopCounting down...4TimerExpires5PromiseResolvedโšก Non-blocking โ€ข ๐ŸŽฏ Efficient โ€ข ๐Ÿ”„ Asynchronous
Understanding the Visualization
1
Create Promise
Initialize a new Promise with resolve callback
2
Set Timer
Use setTimeout to schedule the resolve function
3
Return Promise
Return immediately - non-blocking
4
Timer Expires
setTimeout callback executes and resolves the Promise
5
Promise Resolved
Awaiting code can now continue execution
Key Takeaway
๐ŸŽฏ Key Insight: Use Promise + setTimeout for non-blocking asynchronous delays that don't waste CPU resources
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
58.0K Views
Medium Frequency
~5 min Avg. Time
2.4K 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