Throttle a Function
Throttle limits how often a function runs by allowing at most one call per interval, useful for scroll and resize handlers that fire continuously.
Code
export function throttle(fn, intervalMs) {
let lastCall = 0;
let pendingTimer = null;
return function throttled(...args) {
const now = Date.now();
const remaining = intervalMs - (now - lastCall);
if (remaining <= 0) {
lastCall = now;
return fn.apply(this, args);
}
if (pendingTimer === null) {
pendingTimer = setTimeout(() => {
pendingTimer = null;
lastCall = Date.now();
fn.apply(this, args);
}, remaining);
}
};
}Inside the snippet
The working surface is the functions throttle and throttled — everything else is wiring.
Putting it to use
The primary signature is export function throttle(fn, intervalMs)
Import throttle from the file and call it — the rest of the code is implementation detail.
Core lines
pendingTimer = setTimeout(() => {
pendingTimer = null;
lastCall = Date.now();
fn.apply(this, args);
}, remaining);
return fn.apply(this, args);
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. The file defines `throttle`, `throttled` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.