Sleep Problem
#2621
Description
LeetCode Problem 2621.
Given a positive integer millis, write an asynchronous function that sleeps for millis milliseconds. It can resolve any value.
Note that minor deviation from millis in the actual sleep duration is acceptable.
Example 1:
Input: millis = 100
Output: 100
Explanation: 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
Explanation: It should return a promise that resolves after 200ms.
Constraints:
1 <= millis <= 1000
Solution
Approach: Wrap setTimeout in a Promise
setTimeout takes a callback, not a Promise, so it cannot be awaited directly. Wrap it:
- Return a new Promise whose executor starts a timer for
millismilliseconds. - When the timer fires, call
resolve, so anything awaiting the promise continues after the delay.
The function never blocks: the event loop stays free while waiting, unlike a busy loop that spins until the time passes. The result can be any value, so nothing is passed to resolve.
Complexity: time O(1) work, the delay is waiting time, space O(1).
/**
* @param {number} millis
* @return {Promise}
*/
async function sleep(millis) {
return new Promise((resolve) => setTimeout(resolve, millis));
}
/**
* let t = Date.now()
* sleep(100).then(() => console.log(Date.now() - t)) // 100
*/