ThrottleLoading saved progress…

Throttle

Implement a throttle function that, given a callback fn and a delay wait (ms), returns a new function. The returned function invokes fn immediately on the first call, then ignores every subsequent call for the next wait milliseconds. Once the window passes, the next call invokes fn again and the cycle repeats.

This is the leading-edge variant — calls during the lockout window are dropped, not deferred.

Signature

function throttle(fn, wait) {
  // returns a new function that, when called repeatedly,
  // invokes `fn` at most once per `wait` ms (fire on the leading edge)
}

Examples

const log = throttle((msg) => console.log(msg), 100);

log('a');   // fires immediately → 'a'
log('b');   // dropped (within 100ms lockout)
log('c');   // dropped (within 100ms lockout)

// 150ms later…
log('d');   // fires → 'd'  (cycle resets)
log('e');   // dropped

A common scroll handler:

window.addEventListener('scroll', throttle(updateHeader, 100));
// updateHeader runs at most 10 times per second, regardless of scroll velocity.

Notes

  • Use setTimeout / Date.now() — no external libraries.
  • The first call always fires (leading edge).
  • Calls during the cooldown are discarded, not queued. Only the leading-edge call sees its args.
  • Preserve this if possible (forward via apply / call).
  • Don't worry about a trailing-edge fire, a cancel() method, or a flush() method — those belong to richer variants.
Loading editor…