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
Input: A positive integer
Output: A Promise that resolves after
Note: Minor deviations from the exact millisecond timing are acceptable due to JavaScript's event loop nature.
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
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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code