Throttle
Throttling limits a function to a controlled rate. It is useful when you want updates to continue during a stream of events, without responding to every event.
Implementation
Section titled “Implementation”This version runs immediately when an interval opens and ignores calls until the interval ends.
function throttle(callback, interval) { let lastRun = -Infinity;
return function (...args) { const now = Date.now();
if (now - lastRun >= interval) { lastRun = now; callback.apply(this, args); } };}Example: scroll position
Section titled “Example: scroll position”const reportScroll = throttle(() => { console.log('Scroll position:', window.scrollY);}, 200);
window.addEventListener('scroll', reportScroll);Even if the browser sends many scroll events, reportScroll runs at most once every 200 ms while scrolling continues.
Things to remember
Section titled “Things to remember”- This is a leading edge throttle: the first eligible call runs immediately.
- Calls during the waiting interval are dropped. A trailing edge throttle would also schedule the latest call at the end.
- For visual updates tied to browser repainting,
requestAnimationFramemay be a better fit than a fixed timer.
For the comparison with debounce, see Debounce vs throttle.