Throttle Implementation

Limit function execution to once per time interval.

Code

JavaScript
function throttle(fn, limit) {
  let inThrottle;
  return function (...args) {
    if (!inThrottle) {
      fn.apply(this, args);
      inThrottle = true;
      setTimeout(() => (inThrottle = false), limit);
    }
  };
}

const throttledScroll = throttle(() => console.log("scroll"), 1000);

Line-by-line explanation

Expected output

scroll (once per second)

Related snippets