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.
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)
}
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.
setTimeout / Date.now() — no external libraries.this if possible (forward via apply / call).cancel() method, or a flush() method — those belong to richer variants.