Debouncing vs Throttling in JavaScript

Chanchala Gorale
4 min readSep 20, 2021

Debouncing and throttling are the methods you can use to optimize your website, this prevents unnecessary API calls.

Use case: Search component in an application

Almost every application has a search component to search specific data with keywords.

Some applications use already fetch data and when search components state is changed the function call just filters the data for a given input. In this case, we don't have to worry about the API calls and how they can create load on a server and make it slow.

The above case seems great when you have limited data to filter from. But when you have data that can take forever to load the whole data and then finally filter the fetched data based on a search keyword. In this case, implementing a search based on API calls makes more sense and user friendly.

Problem

While we are trying to solve one problem, we are in fact creating another problem.

There are still two options:

  • Search on button click: This can be a good option where the user knows exactly what there want and is ready to remember exact keywords, which is again not a possible solution.
  • Search as user type the keywords: This is the way all the complex applications are using that has countless data to offer to a user. If a complex application with a huge database and a large user base uses this method, it still creates another issue. Issue of creating load on a server since every time user changes the state of a search component an API call will be made.

Solution

Yes, search as the user types the search keyword is important and it will show the dynamic results as the user enters the search keyword but at the same time if an API call is made every time the state of search component is changed, it will make your server slow since all the dumb API calls are made.

In this case, you can implement the debouncing or throttling method to optimize the API calls made to the server.

Code Reference:
https://codesandbox.io/s/solitary-pine-zhqip?file=/src/App.js

Without debouncing and throttling:
If you call search API every time a search components state is changed to show respective results to a user, it creates a load on a server with all the unnecessary API calls.
eg. if a user wanted to search for a keyword “whiteboard” in an application like Amazon or Flipkart, this will call search API on every letter user has entered in an input element.

//search component
<input
placeholder="search anything here"className="search__bar"onChange={getNormalSearch}/>//functionconst getNormalSearch = (e) => {//add your search logic here//this logic will be called everytime the search input changesconsole.log(e.target.value);};

Debouncing

Debouncing is one of the best practices where you wait for the predefined time period after a user is done entering the desired keyword. Once that time is completed and no further change is made to the search keyword then an API call will be made.

eg. An API will be called only if the user pauses for 500 milliseconds after typing a search keyword.

Explanation:
As explained above debouncing wait for predefined time before calling an API and if that time is interrupted by another change made in the seach keyword the wait time starts again and waits until predefined time.

In JavaScript, we can use setTimeout method to count that predefined time and then execute the function which will dispatch an API call. But since we need to identify an interruption as well we can use and clearTimeout method to strat the setTimeout again from start if the predefined time gap is not yet met

//search component with Debouncing
<input
placeholder="search anything here"className="search__bar"onKeyUp={handleDebounceChange}/>//function
const handleDebounceChange = debouncing(getNormalSearch, 500);
const debouncing = function (fn, wait) {let timer;return function () {clearTimeout(timer);timer = setTimeout(() => {fn.apply(this, arguments);}, wait);
};};

Throttling

Throttling is another best practice used where you limit the API calls by giving a predefined wait time. The API call will be made only once in the given wait time period. This wait time you can specify as per requirement.

eg. An API will be called only once in a 500 millisecond.

Explanation:

Throttling method is like a timer, once the predefined time limit is met an API call will be triggered.

In JavaScript we can achieve throttling by using a setTimeout as we used in the Debouncing but this time we are not clearing a setTimeout method on an interruption. We will add an boolean variable as a flag to check if the specified time limit was met. When search keyword changes again, we will use that flag as a condition where we either trigger an API call or wait until the state of the flag is changed.

//search component with Throttling
<input
placeholder="search anything here"className="search__bar"onKeyUp={handleThrottleChange}/>//functionconst handleThrottleChange = throttling(getNormalSearch, 500);const throttling = (fn, limit) => {let flag = true;return function () {if (flag) {fn.apply(this, arguments);flag = false;setTimeout(() => {flag = true;}, limit);}};};

Debouncing & Throttling Using Lodash

Lodash is JavaScript library, you can check its documentation here: https://lodash.com/docs/4.17.15

Lodash offers predefined debounce and throttling function so all you have to do is that download the loadash library check documentation here: https://www.npmjs.com/package/lodash

npm i lodash

Import lodash in your component

import _ from 'lodash';OR 
//import individual function which you require
import {debounce, throttle} from 'lodash';//Implementation//plain search function
const normalSearch=()=>{
console.log("this is normal search")
}
//debounce function using lodash
const debouncingMethod = debounce(normalSearch, 500);
//throttle function using lodash
const throttlingMethod = throttle(normalSearch, 500);

Drop a clap 👏 , if this was useful for you!!!

--

--