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:
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
});
Another example:
Input: millis
= 200
Output: 200
Explanation: It should return a promise that resolves after 200ms.
Constraints: 1 <= millis <= 1000
The most straightforward way to implement a sleep function in JavaScript is to use setTimeout
. We create a Promise
that resolves after the specified number of milliseconds.
function sleep(millis) {
return new Promise(resolve => setTimeout(resolve, millis));
}
sleep
function takes millis
as an argument, representing the sleep duration.Promise
is created. The Promise
constructor takes a function that receives resolve
as an argument.setTimeout
is called with resolve
as the callback function and millis
as the delay.millis
milliseconds, setTimeout
calls resolve
, which resolves the Promise
.sleep
function returns the Promise
.The provided solution is already quite optimal for its purpose. Since the problem explicitly requests an asynchronous sleep function using Promises, setTimeout
is the standard and efficient tool to achieve this. Further optimization isn't really applicable here.
1 <= millis <= 1000
, the solution should still work if millis
is 0.setTimeout
has some limitations with extremely large values, but the constraint 1 <= millis <= 1000
prevents this from being an issue.setTimeout
function schedules the resolution of the promise. The time taken for setTimeout
to execute is effectively constant, regardless of the millis
value.Promise
and scheduling a timeout.