Typorithm · medium

throttle

throttleinterview-questionsrate-limittimers
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn throttle

0%

Utility Functions

throttle lets fn run at most once per limit milliseconds. The first call fires immediately, then a cooldown flag drops further calls until the interval elapses.

throttle returns a wrapper that enforces a steady maximum rate: fn runs at most once every limit milliseconds no matter how often it is called. It suits scroll, mousemove, and other high-frequency events.

A boolean flag gates the call. The first call passes the gate, runs fn immediately, and sets inThrottle to true; calls during the cooldown are simply ignored.

Contrast with debounce: debounce waits for activity to stop and fires once at the end, while throttle fires regularly during continuous activity at a fixed cadence.

01

Runs fn at most once per interval.

02

First call fires immediately (leading edge).

03

Great for scroll and mousemove handlers.

function throttle(fn, limit) {
  let inThrottle = false;
  return (...args) => {
    if (!inThrottle) {
      fn(...args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Cooldown flag

A boolean tracks whether we are inside the cooldown window.

let inThrottle = false;

2. Gate the call

fn runs only when not currently throttled; otherwise the call is dropped.

if (!inThrottle) {

3. Run immediately

Throttle fires fn right away on the leading edge, then blocks for the interval.

fn(...args);

4. Reopen the gate

After limit milliseconds the flag resets, allowing the next call through.

setTimeout(() => inThrottle = false, limit);

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

throttle: Lesson & Practice · Typorithm | ApplyDjinn