Debouncing and throttling are techniques in JavaScript to control how often a function is executed, especially during events like scrolling, resizing, or typing.

  • Debouncing: Ensures a function runs only after a certain period of inactivity. If the event keeps firing, the function execution is delayed until things “settle down.”
  • Example: Waiting for a user to stop typing in a search box before making an API call.
  • Throttling: Ensures a function runs at most once in a specified time interval, no matter how many times the event fires.
  • Example: Limiting scroll event handling to once every 200ms to avoid performance issues.

TL;DR:

Use debounce for actions triggered after “stopping.”

Use throttle for actions triggered at a controlled, steady rate.