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.

JavascriptResilience

Code

javascriptsnippet
19 lines
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

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.