TobilobaCodes – LeetCode Explorer

2621. Sleep

On this page, we explore LeetCode Problem 2621: Sleep. This problem requires you to implement a function that pauses execution for a specified number of milliseconds.

📄 Problem Statement

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:
let t = Date.now();
sleep(100).then(() => console.log(Date.now() - t));
Output:
~100 (approximately, depending on execution time)

🧠 Explanation

We can use setTimeout inside a Promise to delay execution. This allows us to create a delay function similar to sleep() in other languages. Wrapping it in async lets us use await sleep(millis) wherever needed.

✅ Your Solution


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