Skip to content
JavaScript

Throttle Function

Limit a function to execute at most once within a time interval.

By EZ4Code Team
functionperformancethrottle

Code

function throttle(fn, interval = 300) {
  let lastTime = 0;
  let timer = null;
  return function (...args) {
    const now = Date.now();
    const remaining = interval - (now - lastTime);
    if (remaining <= 0) {
      if (timer) { clearTimeout(timer); timer = null; }
      lastTime = now;
      fn.apply(this, args);
    } else if (!timer) {
      timer = setTimeout(() => {
        lastTime = Date.now();
        timer = null;
        fn.apply(this, args);
      }, remaining);
    }
  };
}

Explanation

Throttle ensures a function executes at most once per fixed interval, suitable for scrolling, dragging, etc.

More JavaScript Snippets