Skip to content
Sleep - 2621

Sleep – 2621

🔗LC2621 🟢 Easy 🧩 Pattern – Promises and Time

📅 Day 13/30 Days of JavaScript

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

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

Solution

The promise will wait until the setTimeout completes and calls the resolve method, and the setTimeout of course waits/sleeps for millis provided.

/**
 * @param {number} millis
 * @return {Promise}
 */
async function sleep(millis) {
    return new Promise((resolve) => setTimeout(resolve, millis))
}

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