Implement Throttle Rate Limiter
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 againThe first call fires at once. Repeat calls inside the window are dropped.
What it has to do
- Execute
fnimmediately on first call. - Ignore subsequent calls made within
waitmilliseconds.
Notes
- This is a _leading-edge_ throttle. A trailing-edge or leading-and-trailing variant is a separate problem.
- 1.executes immediately and throttles secondary calls
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.