Throttle Calls With Leading and Trailing
Limit function execution frequency with configurable leading and trailing edges, plus cancel and flush controls for cleanup.
Code
export function throttle(fn, wait, options = {}) {
if (typeof fn !== "function") throw new TypeError("fn must be a function");
if (!Number.isFinite(wait) || wait < 0) throw new RangeError("wait must be a non-negative number");
const { leading = true, trailing = true } = options;
let timer = null;
let lastInvoke = 0;
let pendingArgs = null;
let pendingThis = null;
let started = false;
function invoke() {
const args = pendingArgs;
const context = pendingThis;
pendingArgs = null;
pendingThis = null;
if (args === null) return;
lastInvoke = Date.now();
fn.apply(context, args);
}
function schedule(delay) {
if (timer !== null) return;
timer = setTimeout(() => {
timer = null;
if (trailing) invoke();
}, delay);
}
function throttled(...args) {
const now = Date.now();
if (!started) {
started = true;
lastInvoke = now;
if (leading) {
fn.apply(this, args);
} else {
pendingArgs = args;
pendingThis = this;
schedule(wait);
}
return;
}
const elapsed = now - lastInvoke;
if (elapsed >= wait) {
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
lastInvoke = now;
pendingArgs = null;
pendingThis = null;
fn.apply(this, args);
return;
}
if (trailing) {
pendingArgs = args;
pendingThis = this;
schedule(wait - elapsed);
}
}
throttled.cancel = () => {
if (timer !== null) clearTimeout(timer);
timer = null;
pendingArgs = null;
pendingThis = null;
started = false;
lastInvoke = 0;
};
throttled.flush = () => {
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
invoke();
};
return throttled;
}
const send = throttle((value) => console.log("sent", value), 200, {
leading: true,
trailing: true,
});
send(1);
send(2);
setTimeout(() => send(3), 250);Output
Captured from a sandboxed run of this snippet in the build pipeline.
sent 1
sent 2
sent 3How it works
Count the functions throttle, invoke, schedule and throttled as the entire surface area of Throttle Calls With Leading and Trailing.
Instead of silently continuing, the code raises TypeError and RangeError at the guard.
What to watch for
- The guard
typeof fn !== "function"short-circuits the flow with an earlythrowwhen its condition holds.
Using it
The primary signature is export function throttle(fn, wait, options = {})
Running the file prints labeled results such as sent — each operation’s effect is visible in the output.
The surface worth importing is throttle; the helpers around it are private to the snippet.
Key statements
if (typeof fn !== "function") throw new TypeError("fn must be a function");
if (!Number.isFinite(wait) || wait < 0) throw new RangeError("wait must be a non-negative number");
setTimeout(() => send(3), 250);
Interactive Tools for This Topic
HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.
FAQ
- What happens on invalid input?
- The code throws `TypeError` and `RangeError` — the guard `typeof fn !== "function"` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. The file defines `throttle`, `invoke`, `schedule` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.