Debouncing

Chen Caijie
2 min readSep 24, 2021

Debouncing is a new performance optimisation method I came across recently during work. It is one of those things that make you wonder: “How did I not know about this earlier?!”

The Story

I was working on a search bar that needed to call an API every time its search input changes in order to update the search results displayed.

You can already see how this can be a problem: every character the user types will trigger an API call. Imagine if the user is the world’s fastest typer at 50 characters per second, the search bar will call the API 50 times per second!

Debouncing

Going back to the problem at hand, we actually don’t need to trigger the API call every time the user types something. We only need to call the API when the user stops typing.

How do we know when the user stops typing?

Debouncing limits the number of times a function is called by introducing a delay. The function will only be triggered after the delay timer ends. If the function is called before the delay timer ends, it resets the delay timer.

Applying this to our example above, if we debounce our search API call, this delay timer will essentially be the amount of time elapsed since the user stopped typing. Hence if we set the delay timer to be 0.5 seconds, the API call will only be performed once the user stops typing for 0.5 seconds.

Writing your own debouncer is easy, here is an example in JavaScript:

/*
* @param func: the function you want to run
* @param delay: the delay timer in milliseconds
* @returns a debounced version of the original function
*/
function debounce(func, delay) {
let timerId = null; // use this to decide when to clear timeout
return (...params) => {
// reset delay if there is already a timeout scheduled
if (timerId) {
clearTimeout(timerId);
}
// schedule to run the function after timeout
timerId = setTimeout(() => {
func(...params);
timerId = null; // remember to reset here!
}, delay);
}
}

--

--