Hiprup

How do you implement a simple throttle function?

Throttle ensures a function runs at most once per time window, however often it's triggered.

  1. Record the last run time (or a "ready" flag).

  2. On each call, if enough time has passed, run the function and update the timestamp.

  3. Otherwise ignore the call.

Good for scroll, resize, and mousemove handlers, where running on every event is wasteful.

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

// Usage: scroll handler at most every 100ms
const onScroll = throttle(() => {
  console.log('Scroll:', window.scrollY);
}, 100);

window.addEventListener('scroll', onScroll);

Tracks lastTime of execution. On each call, checks if enough time has passed. If yes: execute and update lastTime.

If no: skip (do nothing). fn.apply preserves this context. Unlike debounce (which delays execution), throttle ensures periodic execution.

Simpler than debounce: just check elapsed time. throttle = regular rate limit, debounce = wait for pause. Use for: scroll, resize, mousemove.

Show the time check: now - lastTime >= interval.

How do you implement a simple throttle function? | Hiprup