What is debouncing?


Debouncing is a mechanism in which we defer a certain operation until the user stops providing input to the application”.

A very common example where debouncing is used is the search box on e-commerce websites. When we type something in the search box, we see the related search results in the dropdown. These results are fetched by calling some API in which the search text is sent as input.

Now, just think about the volumes of API calls handled by the servers of the e-commerce application if millions of people are searching for something and on each keystroke, we are making an API call to fetch the results.

This problem, on the client’s side, is resolved using debouncing. So, in this case, we will not make an API call on every keystroke, instead we will do so once the user pauses for some time, say, 500ms.

This way we will reduce the API calls from number of keystrokes to number of pauses which are longer than a specific amount of time. Thereby, reducing the number of calls with a large factor.

Implementation

Let’s take a very simple example where we will write a debounce function and see how it is used.

Suppose we have an input box and we want to print its value in a div on the same page. The condition here is that we want to update the inner text of the div only when the user stops typing i.e., we do not want to update the div on each keystroke.

HTML

<!DOCTYPE html>
<html>

<head>
    <title>Debounce example</title>
</head>

<body
    style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;">
    <div style="padding: 10px;">
        <span>Enter text - </span>
        <input type="text" onkeyup="onInputKeyUp(event)">
        <br />
    </div>

    <div style="padding: 10px;">You typed:</div>
    <div id="message" style="padding: 10px; font-style: italic;"></div>

    <script src="./debounce.js"></script>
</body>

</html>

We want to update the div with id “message” with the content of the input box after the user stops typing.

JS

const debounceFun = debounce(printMessage);

function onInputKeyUp(event) {
    console.log(`keyup event`);
    debounceFun(event.target.value);
}

function printMessage(message) {
    console.log(`printing message ${message}`);
    document.getElementById('message').innerText = message;
}

function debounce(func, delay = 500) {
    let timer = null;

    return (...args) => {
        if (timer) {
            clearInterval(timer);
        }

        timer = setTimeout(() => {
            func(...args);
            timer = null;
        }, delay);
    };
}

Here, we are calling the debounce function with the function as an argument which we want to call after a delay. It will return a new function which will implicitly call the original function (printMessage) after some time. Note that, here we are using the closure property of JavaScript to achieve debouncing.

Output

If we look at the console, we can see that our message is printed after we type 13 characters in the input box indicating that our debounce method worked.