How to throttle and debounce events in JavaScript

· Category: JavaScript

Short answer

Throttling limits execution to once per time window, while debouncing delays execution until the event stops firing for a specified duration.

Steps

  1. Implement debounce: javascript function debounce(fn, delay) { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); }; } window.addEventListener("resize", debounce(() => console.log("resized"), 200));
  2. Implement throttle: javascript function throttle(fn, limit) { let inThrottle; return (...args) => { if (!inThrottle) { fn(...args); inThrottle = true; setTimeout(() => inThrottle = false, limit); } }; } window.addEventListener("scroll", throttle(() => console.log("scrolled"), 100));

Tips

  • Use debounce for search inputs and form validation.
  • Use throttle for scroll and resize handlers to maintain frame budget.

Common issues

  • Forgetting to return the wrapper function from the utility.
  • Not handling the trailing edge in debounce, which can miss the final update.