Photo by James Harrison on Unsplash

Debouncing & Throttling in JavaScript

Chidanandan P
Nerd For Tech
Published in
4 min readJul 10, 2021

--

Debouncing and throttling are techniques in javascript to optimise the application and browser performance.

What is a debounce function?

Debounce function limits the execution of a function call and waits for a certain amount of time before running it again.

Let’s take a real world scenario where we use this the most.

Most of the websites have search bar which helps the user to search with a specific keyword to get what they want. If we take e-commerce use-case, when the user tries to search a specific product, one can see multiple suggestions popping up even before he enters the entire keyword.

So what’s happening here is once the user starts typing the keyword we are making API call for each of the character. If the user types “Apple MacBook Pro”, then 17 times (including spaces) we have made API calls to get the results.

This approach is not ideal even though we have the best intention in mind to display suggestions to user while he still typing.

We can optimise and reduce the count of API calls by debounce logic. We can wait for certain amount of time before making the next API call.

Here we monitor the delay user gives between two key presses. If this delay matches our threshold limit, then we make another API call.

Let’s keep 500ms as threshold limit for this delay, it means if the user takes 500ms or more to type the next character, only then we make our next API call. Ideally when the user is typing “Apple MacBook Pro”, he takes 500ms or more delay between each key press is only 3 to 5 times. This way we can reduce the count of API calls from 17 to just 3-5.

Let’s see how our code looks with first scenario where 17 API call happens for “Apple MacBook Pro”

Usually we will be handling search functionality with onChange or onKeyUp events.

<inputclassName="search-bar"onChange={ searchHandler }/>

searchHandler function will look something like this:

function searchHandler(...args){/* capture the search query entered by customer */
const { value } = args[0].target;
/* Make an API call with search query */
getSearchResults(value);
}

Now let’s see how we can write a reusable debounce function with searchHandler and delay threshold as parameters:

const optimisedSearchHandler = debounceFunc(searchHandler, 500)const debounceFunc = (func, delay) => {
let timer;
return function(...args) {
const context = this;
clearTimeOut(timer);
timer = setTimeOut(() => {
func.apply(context, args);
}, delay)
}
}

debounce function logic break-up:

Now we can pass optimisedSearchHandler to our search bar input onChange event

<inputclassName="search-bar"onChange={ optimisedSearchHandler }/>

This way we can avoid multiple time execution of any expensive functions like searchHandler with user behaviour based logic.

What is throttle function?

Throttling is a technique, to limit the execution of an event handler function, even when this event triggers continuously due to user actions. (ex: browser resizing)

Let’s take an example of a shooting game, where user pulls the trigger of a weapon continuously. We need to take care the Rate of Fire for different type of weapons.

Shotgun might take more time interval between two rounds of fire, where as machine guns take less interval. But the challenge here is, usually user clicks on trigger button continuously and we need to take care of the time interval between each shot.

Let’s say shotguns take 500ms to fire the next round and machine guns take just 100ms. We need to write the logic such that even if the user clicks on trigger button before this threshold, we should hold the fire according to the weapon’s Rate of Fire.

Event handler for trigger click:

window.addEventListener(onclick, handlerTrigger);const handlerTrigger = () => {  fireShot();      // Expensive call}

Above code call the handlerTrigger function every time user clicks on certain button.

Now let’s see how we can write a reusable throttle function with handlerTrigger and interval as parameters:

const optimisedTriggerHandler = throttleFunc(handlerTrigger, 100);const throttleFunc = (func, interval) => {
let shouldFire = true;
return function() {
if (shouldFire) {
func();
shouldFire = false; setTimeOut(() => {
shouldFire = true;
}, interval)
}
}
}

throttle function logic break-up:

Now we can pass optimisedTriggerHandler to onclick event listener:

window.addEventListener(onclick, optimisedTriggerHandler);

This way we can make copy of optimisedTriggerHandler for different weapons with different time intervals.

To understand how apply method works, checkout my article on call, apply and bind in JavaScript.

Summary:

  1. Debouncing is a technique where we can monitor the time delay of user action and once that delay reaches our predetermined threshold we can can make the function call.
  2. Throttling is a technique where we make the function call in a predetermined time interval irrespective of continuous user actions.
  3. Even though both debouncing and throttling seems like similar, both have their own use-cases. It’s not recommended to use throttling logic in search bar and we we cannot use debouncing in shooting game scenario or browser resizing or onScroll events.

Chidanandan P ( if the name is difficult to pronounce call him Chidu ) is a software development engineer at Maersk, where he helps in building the technology and solutions that powers Lowe’s and its various businesses.

--

--

Chidanandan P
Nerd For Tech

Software Engineer. Building solutions to various e-commerce / logistics. Predominantly codes in JavaScript & its libraries such as ReactJs, React Native.