Talentd
FleetCode

2621. Sleep

Easy87.3% acceptance3 companies

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

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

Asked at 3 companies

Hints open one at a time

Hint 1
In Javascript, you can execute code after some delay with the setTimeout(fn, sleepTime) function.
Hint 2
An async function is defined as function which returns a Promise.
Hint 3
To create a Promise, you can code new Promise((resolve, reject) => {}). When you want the function to return a value, code resolve(value) inside the callback.
19:13
Still stuck?Read 5 approaches, or watch a walkthrough.
Open solution
Loading editor…
1/**
2 * @param {number} millis
3 * @return {Promise}
4 */
5async function sleep(millis) {
6
7}
8
9/**
10 * let t = Date.now()
11 * sleep(100).then(() => console.log(Date.now() - t)) // 100
12 */
Starter codeJavaScriptSpaces: 4
Examples
Input
100
Input
200
Your code is saved on this device.Solution