What is Debouncing?. Debouncing is something that comes up… | by Jamis Charles | Medium

What is Debouncing?

Jamis Charles
2 min readJul 29, 2018

--

Debouncing is something that comes up fairly frequently in UI development. In the last few years I’ve encountered several interview questions where debouncing was the solution. So here’s a brief overview of debouncing.

What is debouncing?

Debouncing a function ensures that it doesn’t get called too frequently.

Why debounce? What problem does it solve?

Say you want to move a box on the page every time you scroll the browser window. Usually you start by adding some code like this:

Browser scroll listener example

Code like this will work, but very quickly causes performance issues. Here’s why: If you scroll the browser window say 100px, the scrollHandler() function code will run very often. Anywhere from dozens to hundreds of times. Depending on the code this could cause a scroll experience that feels stuttery. Usually in situations like this you want the scrollHandler() function to run only when the scroll ends. This is what debouncing does for us.

Debouncing says “wait until this function hasn’t been called in x time, and then run it”. All the prior calls get dropped. Input typeaheads are another common use case. Debouncing all the ajax calls avoids causing performance issues for the server.

A simple debounce implementation

A simple debounce implementation

Above we see a simple implementation, and a test case. I was asked this question during my Facebook Front-end interview several years ago.

What should I use in production?

Generally I don’t write my own custom debounce function when I need to use it. I usually use the lodash version, which is great. You can even load only debounce() from lodash, which is what I usually do. Works great!

--

--

Jamis Charles
Jamis Charles

Written by Jamis Charles

UI Engineer at PayPal. @jamischarles — Questions to: Questions? https://github.com/jamischarles/ama -> Thoughts are my own. Blog at https://jamischarles.com.