How to implement debounce and throttle in JavaScript

Click for: original source

At some point you have probably come across a website that uses an autocomplete text box, drag and drop, or scroll based animations. If you have then chances are also pretty high that you have encountered debouncing and/or throttling without even realizing it. By @webdevsimplified.com.

First I want to talk about debounce since debounce is the ideal solution for things like autocomplete text boxes. Debouncing works by delaying our function call by a set period of time. If nothing happens during that time then the function will run just like normal, but if something happens that causes the function to be called again during the delay then the delay will be restarted.

Like debounce, throttle is also used to limit the number of times a function is called, but, unlike debounce, throttle will call the function passed to it every time the delay ends as long as the trigger for the function is still happening. For example, if our delay is set to 1 second then our throttled function will execute immediately when it is called and then at most once per second while the user is actively typing.

Anytime you are dealing with groups of events that you want to group together debounce and throttle are perfect. They save you money on server costs, save your users money on data costs, and overall make your app more performant. Nice one!

[Read More]

Tags app-development web-development javascript programming