Debouncing and Throttling in JavaScript

Debounce

Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. For example, “execute this function only if 100 milliseconds have passed without it being called.”

Throttle

Throttling enforces a maximum number of times a function can be called overtime. For example, “execute this function at most once every 100 milliseconds.”

When to use each

Use debounce when you want your function to postpone its next execution until after X milliseconds have elapsed since the last time it was invoked.

  • Measure the scroll position of the page — The browser will fire the scroll binding event every single time the user scrolls, which can result in many events per scroll. If the binding event performs several repaints, this spells bad news for the end-user; layout reflows and repaints are expensive, especially when you are redrawing large parts of the view, as is the case when there is a scroll event.
  • Wait until the user stops resizing the window — Window resizes operations cause various child elements to update themselves by resizing and reorganizing themselves. By throttling, you can delay the resize events and fire fewer of those resizing events.
  • Fire Ajax calls under control and avoids unnecessary network request handling — for example, in case of searching for external data, wait until the end-user stops typing by using debounce. If you are sending log data frequently, use a throttle.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhay Jain

Abhay Jain

Developer with 3 yrs of industrial experience in developing scalable web applications.