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
- Wrap
setTimeoutin anew Promise, callingresolveinside the timer callback. - Declaring the function
asynclets callersawait sleep(100). - The equivalent one-liner is
return new Promise(resolve => setTimeout(resolve, millis));. - The exercise targets how a Promise executor runs synchronously at construction time while
resolvedecides 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
sleeppauses the whole thread: it only suspends the currentasyncfunction. - Forgetting to return the Promise: the
asyncwrapper would still work, but returning it explicitly is clearer.