ESC

Type to search the knowledge base.

SnippetJavaScript

Throttle

Invoke at most once per interval while events keep firing — scroll, mousemove, resize.

Explanation

Throttle ensures a minimum spacing between calls. This leading+trailing-style version fires on the leading edge and schedules a trailing call if events continued.

javascript
export function throttle(fn, wait = 100) {
  let last = 0;
  let timer;
  return function throttled(...args) {
    const now = Date.now();
    const remaining = wait - (now - last);
    const ctx = this;
    if (remaining <= 0) {
      clearTimeout(timer);
      timer = undefined;
      last = now;
      fn.apply(ctx, args);
    } else if (!timer) {
      timer = setTimeout(() => {
        last = Date.now();
        timer = undefined;
        fn.apply(ctx, args);
      }, remaining);
    }
  };
}

Usage example

javascript
const onScroll = throttle(() => {
  console.log(window.scrollY);
}, 100);

window.addEventListener('scroll', onScroll, { passive: true });

Interview tips

  • Use passive: true for scroll listeners when you don’t preventDefault.
  • For animation, prefer requestAnimationFrame over throttle.

Related

← All snippets