Write a function `delay(ms)` that returns a Promise that resolves after the specified milliseconds.
Problem Statement
<p>Write a function <code>delay(ms)</code> that returns a Promise that resolves after the specified milliseconds.</p>
Examples
Input: await delay(100)
Output: Promise resolves after 100ms
Explanation: Promise completes after timer fires.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
š” Hint 1:
Use the Promise constructor.
š” Hint 2:
Use setTimeout inside the promise executor.
š” Hint 3:
return new Promise(resolve => setTimeout(resolve, ms));
Editorial & Approach
Problem Overview & Intuition
To solve Delay Function, we consider the execution characteristics of JavaScript engines. Write a function `delay(ms)` that returns a Promise that resolves after the specified milliseconds. By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.
Step-by-Step Approach
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (use the promise constructor).
- Implement Logic: Handle state and transformations efficiently (use settimeout inside the promise executor).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
Complexity Analysis
Time Complexity
O(N) linear scan over input
Space Complexity
O(1) constant auxiliary space (or O(N) output)
Edge Cases & Corner Traps Handled
- Empty or boundary inputs (empty arrays, strings, zero length).
- Type checks and unexpected values (e.g.
null,undefined, negative numbers). - Closure preservation and memory isolation between separate invocations.