Skip to content
GreenSnippets

Throttle a function

Run a function at most once per interval, calling immediately and again at the end of a burst.

JavaScript
function throttle(fn, interval = 200) {
  let last = 0;
  let timer;
  let pendingArgs;
  return function throttled(...args) {
    const now = Date.now();
    const remaining = interval - (now - last);
    pendingArgs = args;
    if (remaining <= 0) {
      clearTimeout(timer);
      timer = undefined;
      last = now;
      fn.apply(this, args);
    } else if (!timer) {
      timer = setTimeout(() => {
        last = Date.now();
        timer = undefined;
        fn.apply(this, pendingArgs);
      }, remaining);
    }
  };
}

How it works

Throttling guarantees a function runs at most once every interval ms. This version fires immediately (leading edge) and also schedules one trailing call with the latest arguments, so the final state is never lost, which suits scroll and resize handlers.

Prefer requestAnimationFrame for purely visual updates.