Skip to content

2621. Sleep

Description

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

Solutions

Solution 1

Thinking

We need an awaitable delay; setTimeout is not a Promise. A busy loop would block the event loop.

Wrapping the timer in a Promise resolves when it fires, so callers continue asynchronously.

Hence sleep returns new Promise(r => setTimeout(r, millis)).

1
2
3
4
5
6
7
8
async function sleep(millis: number): Promise<void> {
    return new Promise(r => setTimeout(r, millis));
}

/**
 * let t = Date.now()
 * sleep(100).then(() => console.log(Date.now() - t)) // 100
 */
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
/**
 * @param {number} millis
 * @return {Promise}
 */
async function sleep(millis) {
    return new Promise(r => setTimeout(r, millis));
}

/**
 * let t = Date.now()
 * sleep(100).then(() => console.log(Date.now() - t)) // 100
 */

Comments