Taro Logo

Sleep

Easy
Apple logo
Apple
1 view

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

Solution


Naive Solution

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));
}

Explanation

  1. The sleep function takes millis as an argument, representing the sleep duration.
  2. A new Promise is created. The Promise constructor takes a function that receives resolve as an argument.
  3. setTimeout is called with resolve as the callback function and millis as the delay.
  4. After millis milliseconds, setTimeout calls resolve, which resolves the Promise.
  5. The sleep function returns the Promise.

Optimal Solution

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.

Edge Cases

  • millis = 0: The promise will resolve almost immediately. Though the problem states 1 <= millis <= 1000, the solution should still work if millis is 0.
  • Large millis: setTimeout has some limitations with extremely large values, but the constraint 1 <= millis <= 1000 prevents this from being an issue.
  • Negative millis: While the problem specifies a positive integer, handling a negative value gracefully might be considered. One could throw an error or treat it as zero.

Big O

  • Time Complexity: O(1) The setTimeout function schedules the resolution of the promise. The time taken for setTimeout to execute is effectively constant, regardless of the millis value.
  • Space Complexity: O(1) The space required is constant, as it only involves creating a new Promise and scheduling a timeout.