Implement throttle function

MediumTechnical
NetflixFrontend Engineer
198

Write a throttle function that limits the rate at which a function can be called. It should invoke the function at most once per specified time period.

1 Answer

145
Top Answer

Throttle ensures a function runs at most once per time period:

function throttle(func, limit) {
  let inThrottle = false;

  return function(...args) {
    if (!inThrottle) {
      func.apply(this, args);
      inThrottle = true;
      setTimeout(() => {
        inThrottle = false;
      }, limit);
    }
  };
}

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

Throttle vs Debounce

ThrottleDebounce
Runs at regular intervalsRuns after user stops
Good for: scroll, resizeGood for: search input
"At most once per X ms""Wait X ms after last call"
ThrottleMaster

Share Your Answer

Help others by sharing your knowledge and experience with this question.

Coming soon...

Related Questions

View all

More from Netflix

View all