LeetCode Problem Workspace
Sleep
Create an asynchronous function that sleeps for a given number of milliseconds and resolves any value.
0
Topics
2
Code langs
0
Related
Practice Focus
Easy · Sleep core interview pattern
Answer-first summary
Create an asynchronous function that sleeps for a given number of milliseconds and resolves any value.
Ace coding interviews with Interview AiBoxInterview AiBox guidance for Sleep core interview pattern
The problem requires an asynchronous function that delays execution for a specified number of milliseconds. This is a straightforward implementation using JavaScript's setTimeout function wrapped inside a promise to mimic a sleep behavior. The challenge is to ensure accuracy while keeping the solution efficient and simple.
Problem Statement
You are given a positive integer millis, which represents the number of milliseconds to sleep. Write an asynchronous function that pauses execution for the given time in millis and resolves any value after the sleep duration.
Your solution should ensure that the promise resolves after the given number of milliseconds. The exact sleep time may vary slightly due to system timing, but the resolution must happen close to the specified duration.
Examples
Example 1
Input: millis = 100
Output: 100
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
It should return a promise that resolves after 200ms.
Constraints
- 1 <= millis <= 1000
Solution Approach
Use setTimeout to Implement Sleep
To solve the problem, the sleep function can use JavaScript's setTimeout function to delay the execution of code for a given duration. Wrapping this inside a promise ensures that the function behaves asynchronously and allows chaining with .then or using await.
Handling Accuracy with setTimeout
Since setTimeout is not guaranteed to be exact down to the millisecond due to system-level delays, the implementation can accept slight deviations. Ensure that the deviation does not affect the functionality or behavior of the code significantly.
Consideration for Edge Cases
Make sure to handle edge cases such as very small values (like 1ms) or the maximum limit of 1000ms. The function must reliably resolve within the given range, even if the resolution time slightly differs due to system performance.
Complexity Analysis
| Metric | Value |
|---|---|
| Time | Depends on the final approach |
| Space | Depends on the final approach |
The time complexity depends on the system's timing mechanisms. The space complexity is O(1) because only the setTimeout function and the promise are used, requiring constant space.
What Interviewers Usually Probe
- Candidates should demonstrate familiarity with asynchronous JavaScript and promise handling.
- Ensure candidates discuss potential deviations when using setTimeout for precise timing.
- Look for candidates to handle edge cases and guarantee resolution within a given time range.
Common Pitfalls or Variants
Common pitfalls
- Using setTimeout incorrectly, such as not wrapping it in a promise.
- Misunderstanding the non-deterministic nature of timing in JavaScript and expecting precise resolution.
- Not handling edge cases where millis is extremely small or close to the upper constraint.
Follow-up variants
- Implement a sleep function using async/await.
- Modify the problem to accept an array of millis values, where the function sleeps for each value in the array sequentially.
- Extend the problem to include a timeout option where the function rejects if the sleep time exceeds a certain threshold.
FAQ
How do I implement the sleep function for this problem?
You can use setTimeout inside a promise to delay the function execution for the given milliseconds. Ensure the promise resolves after the specified delay.
What if the sleep duration is not exact?
Minor deviations in the actual sleep time are acceptable, as setTimeout is not guaranteed to be exact. However, it should be close enough to the given millis value.
What is the primary challenge of this problem?
The challenge is correctly using asynchronous programming to delay execution for the specified time and ensuring the function resolves accurately.
How do I handle edge cases like very small or large millis?
Handle edge cases by ensuring that the function works within the specified range, from 1ms to 1000ms, while accounting for slight timing discrepancies.
What is the time complexity of the sleep function?
The time complexity is dependent on the system's handling of setTimeout. The space complexity is O(1) since only a promise and setTimeout are involved.
Solution
Solution 1
#### TypeScript
/**
* @param {number} millis
* @return {Promise}
*/
async function sleep(millis) {
return new Promise(r => setTimeout(r, millis));
}
/**
* let t = Date.now()
* sleep(100).then(() => console.log(Date.now() - t)) // 100
*/