What is Debouncing?
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:
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
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!