AniUI Academy

Implement Throttle Rate Limiter

mediumFunctions & ClosuresHigh freq+250 XPFrontend AlgoArena

Throttling guarantees that a function runs at most once in a given window — the opposite of debounce. Where debounce waits for silence before firing, throttle fires immediately and then quietens down.

This is what you reach for on scroll, resize, mousemove and similar high-frequency event streams, where every event is cheap but handling every one would hammer the main thread.

Implement throttle(fn, wait) returning a wrapped function. The first call to the wrapper runs fn immediately; any additional calls within the next wait milliseconds are ignored.

Arguments

fnFunction
The callback to throttle.
waitnumber
The minimum milliseconds between actual invocations of fn.

Returns

Function — A throttled wrapper around fn.

Examples

let i = 0;
const inc = throttle(() => { i++; }, 50);

inc(); // runs — i === 1
inc(); // ignored (within window)
inc(); // ignored
// 60ms later: window has passed; next call runs again

The first call fires at once. Repeat calls inside the window are dropped.

What it has to do

  • Execute fn immediately on first call.
  • Ignore subsequent calls made within wait milliseconds.

Notes

  • This is a _leading-edge_ throttle. A trailing-edge or leading-and-trailing variant is a separate problem.
Asked atMetaGoogleAmazonUber
Try it yourself
Loading playground...
1 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.