Explorer
JavaScript

Write a function `throttle(fn, limit)` that ensures fn is called at most once every limit milliseconds.

Problem Statement

<p>Write a function <code>throttle(fn, limit)</code> that ensures fn is called at most once every limit milliseconds.</p>

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

šŸ’” Hint 1: Throttle limits the rate of function calls. šŸ’” Hint 2: Track whether the function is in a "cooldown" period. šŸ’” Hint 3: Use a flag: if not throttled, call fn and set flag to true. Use setTimeout to reset flag after limit ms.

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

  1. Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
  2. Choose Core Mechanism: Use modern JavaScript patterns (throttle limits the rate of function calls).
  3. Implement Logic: Handle state and transformations efficiently (track whether the function is in a "cooldown" period).
  4. 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

Time Complexity O(1) wrapper invocation overhead
Space Complexity O(1) closure scope retention

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.

Throttle Function

Hard

Write a function throttle(fn, limit) that ensures fn is called at most once every limit milliseconds.

Example Scenarios
1Example 1
Input: const throttled = throttle(fn, 200); throttled(); throttled();
Output: fn called at most once every 200ms
Explanation:

Enforces execution rate limit.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
1