NeetCode #954LC-2621EasyJavaScript
← Back to All Problems

#954 · #2621 · Sleep(睡眠函数)

📌 Problem Statement & Constraints

Implement sleep(millis), which returns a Promise that resolves after millis milliseconds. It enables await sleep(100) to pause an async flow.

💡 Core Algorithmic Approaches

  1. Wrap setTimeout in a new Promise, calling resolve inside the timer callback.
  2. Declaring the function async lets callers await sleep(100).
  3. The equivalent one-liner is return new Promise(resolve => setTimeout(resolve, millis));.
  4. The exercise targets how a Promise executor runs synchronously at construction time while resolve decides when it settles.

💻 Benchmark Python3 Implementation

async function sleep(millis) {
    // setTimeout calls resolve after millis, settling the Promise
    return new Promise(resolve => setTimeout(resolve, millis));
}

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(1): constant time, not counting the wait itself.
💾 Space Complexity
O(1): one timer.

⚠️ Interview Pitfalls & Follow-ups

  • Calling resolve() immediately in the executor: there would be no delay at all.
  • Busy-waiting to block: that would stall the event loop, which is never acceptable in JavaScript.
  • Assuming sleep pauses the whole thread: it only suspends the current async function.
  • Forgetting to return the Promise: the async wrapper would still work, but returning it explicitly is clearer.