Problem#
Given a positive integer millis
, write an asynchronous function that sleeps for millis
milliseconds. It can resolve any value.
Examples#
Example 1#
1
2
3
4
5
6
7
Input: millis = 100
Output: 100
Explanation: It should return a promise that resolves after 100 ms.
let t = Date. now ();
sleep( 100 ). then (() => {
console. log ( Date. now () - t); // 100
});
Example 2#
1
2
3
Input: millis = 200
Output: 200
Explanation: It should return a promise that resolves after 200 ms.
Constraints#
Solution#
Method 1 – Promise with setTimeout#
Intuition#
To “sleep” in JavaScript, return a Promise that resolves after a timeout.
Approach#
Use setTimeout to delay the resolution of a Promise by the given milliseconds.
Return the Promise from the function.
Code#
Javascript
1
2
3
4
5
6
7
/**
* @param {number} millis
* @return {Promise<void>}
*/
function sleep (millis ) {
return new Promise(resolve => setTimeout (resolve , millis ));
}
Complexity#
⏰ Time complexity: O(1)
— setTimeout is scheduled in constant time.
🧺 Space complexity: O(1)
— No extra space used.