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

snippet
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);
    }
  };
}