Exercise 12: Throttle Function (rate limiting)

Problem Statement

Create a function `throttle(fn, delay)` that throttles a function. If multiple calls occur within delay, only the first call executes. Example: Throttled function with 500ms delay, 3 rapid calls → only 1st call executes

Sample Output:

const throttled = throttle(() => console.log("called"), 500);
throttled(); throttled(); throttled();
// Only first call executes, others ignored within 500ms

Solution

const throttle = (fn, delay) => {
  let lastCall = 0;
  return (...args) => {
    const now = Date.now();
    if (now - lastCall >= delay) {
      lastCall = now;
      return fn(...args);
    }
  };
};

Explanation

Overall Goal:

  • Function calls ko rate limit karna.
  • Delay period me sirf first call execute, baaki ignore.

Line 1: Function header

  • const throttle = (fn, delay) => {

Line 2: Track last call

  • let lastCall = 0;
  • Last execution time store.

Line 3: Return throttled function

  • return (...args) => {
  • Throttled version return.

Line 4: Current time

  • const now = Date.now();

Line 5: Check delay

  • if (now - lastCall >= delay)
  • Kya delay period complete ho gaya?

Line 6-7: Execute if allowed

  • lastCall = now; → update timestamp.
  • return fn(...args); → original function call.

Real world:

  • Scroll events: performance optimization.
  • Resize events: window resize handling.
  • API calls: prevent excessive requests.