JavaScript Beginner

Throttle a Function

Throttling ensures a function runs at most once per interval, no matter how often it’s called. Ideal for scroll or resize handlers.

JavaScript
function throttle(fn, wait) {
  let last = 0;
  return function (...args) {
    const now = Date.now();
    if (now - last >= wait) {
      last = now;
      fn.apply(this, args);
    }
  };
}

Usage notes

Wrap any expensive handler: window.addEventListener('scroll', throttle(onScroll, 200));