Write a function `throttle(fn, limit)` that ensures fn is called at most once every limit milliseconds.
Problem Statement
Examples
Input: const throttled = throttle(fn, 200); throttled(); throttled();
Output: fn called at most once every 200ms
Explanation: Enforces execution rate limit.
Complexity
Time Complexity: O(1)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
To solve Throttle Function, we consider the execution characteristics of JavaScript engines. Write a function `throttle(fn, limit)` that ensures fn is called at most once every limit 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 (throttle limits the rate of function calls).
- Implement Logic: Handle state and transformations efficiently (track whether the function is in a "cooldown" period).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function throttle(fn, limit) {
let inThrottle = false;
return function(...args) {
if (!inThrottle) {
fn.apply(this, args);
inThrottle = true;
setTimeout(() => { inThrottle = false; }, limit);
}
};
}
Complexity Analysis
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.