We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Sleep

Difficulty: Easy


Problem Description

Given a positive integer millis, write an asynchronous function that sleeps for millis milliseconds. It can resolve any value.


Key Insights

  • The function should return a promise that resolves after a specified duration.
  • The duration is provided in milliseconds.
  • The implementation must ensure that the promise resolves after the precise time delay.

Space and Time Complexity

Time Complexity: O(1) - The function itself does not depend on the size of the input, only on the fixed delay. Space Complexity: O(1) - The function does not use any additional data structures that grow with input size.


Solution

The solution involves creating an asynchronous function that uses a timing mechanism to delay execution. The setTimeout function is appropriate for this, as it allows us to specify a delay after which a callback (in this case, the resolution of the promise) is executed. The function will return a promise that resolves after the specified amount of time has elapsed.


Code Solutions

function sleep(millis) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(millis);
        }, millis);
    });
}

// Example usage:
let t = Date.now();
sleep(100).then(() => {
    console.log(Date.now() - t); // Should output approximately 100
});
← Back to All Questions