Throttling

What is Throttling?

Throttling runs a function at most once every N milliseconds while the event keeps firing. Good for scroll, resize, mouse move and button spam.

Example

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

const onScroll = throttle((i) => console.log('handled scroll event', i), 50);
let i = 0;
const id = setInterval(() => {
  onScroll(++i);                 // fires every 10 ms
  if (i === 20) clearInterval(id);
}, 10);

Output

handled scroll event 1
handled scroll event 5
handled scroll event 9
handled scroll event 13
handled scroll event 17

Debounce vs Throttle

DebounceThrottle
Runsonce, after activity stopsregularly, at most every N ms
Use forsearch box, auto-save, validationscroll, resize, mouse move, infinite scroll
Librarieslodash.debouncelodash.throttle