Open In App

Implement Search Box with debounce in JavaScript

Last Updated : 15 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Debouncing is an optimization technique to limit the number of times a task is done. For example – in e-commerce sites, when we search for some product in the search box, a lot of network calls can be made for fetching a list of products for that particular keyword, debounce is used in such cases to make fewer network calls.

Problem statement: First, we will see the output of a search box that doesn’t use any debouncing technique.

HTML




<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
</head>
  
<body>
    <input />
    <div class="result-container"></div>
    <script src="src/index.js"></script>
</body>
</html>


CSS




body {
    font-family: sans-serif;
}
  
.item {
    margin-top: 10px;
    font-family: Cambria, Cochin, Georgia, Times, "Times New Roman", serif;
    background-color: ghostwhite;
    height: 50px;
    color: green;
}


Javascript




import "./styles.css";
  
const input = document.querySelector("input");
const container = document.querySelector(".result-container");
  
const makeAPICall = (searchValue) => {
    container.innerHTML = "";
    if (!searchValue) {
        return;
    }
  
    // Use the API link to see the result
    fetch(`https://api.../v2/beers?beer_name=${searchValue}`)
        .then((res) => {
            res.json().then((response) => {
                console.log(response)
                response.forEach((item) => {
                    const div = document.createElement("div");
                    div.textContent = item.name;
                    div.classList.add("item");
                    container.appendChild(div);
                });
            });
        })
        .catch((e) => { });
};
  
  
input.addEventListener("input", (e) => {
    makeAPICall(e.target.value);
});


Output:

Implement Search Box with debounce in javascript

Implement Search Box with debounce in javascript

As we can see above on each character was entered an API call was made, since these API calls are expensive it’s not recommended to make too many API calls.

Now, we will see how we can make fewer API calls by using debounce technique. Let’s implement a search box that will make fewer network calls.

Approach:

  • We will create a debounce function. This function will take two inputs, one will be the fn function which we want to call when some input is entered and another will delay input, by this much we will delay calling the fn function. This debounce function will return a function that will be stored inside a variable onInput. The fn input function will be the one that will make an API call to the back-end with the input entered. This means that the API call will be made delay ms after the user stops providing input.
  • Now, whenever a character is entered as input then we will call onInput function.

HTML




<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
</head>
  
<body>
    <input />
    <div class="result-container"></div>
    <script src="src/index.js"></script>
</body>
</html>


CSS




body {
    font-family: sans-serif;
}
  
.item {
    margin-top: 10px;
    font-family: Cambria, Cochin, Georgia, Times, "Times New Roman", serif;
    background-color: ghostwhite;
    height: 50px;
    color: green;
}


Javascript




import "./styles.css";
  
const input = document.querySelector("input");
const container = document.querySelector(".result-container");
  
const makeAPICall = (searchValue) => {
    container.innerHTML = "";
    if (!searchValue) {
        return;
    }
  
    // Use the API link to see the result
    fetch(`https://api.../v2/beers?beer_name=${searchValue}`)
        .then((res) => {
            res.json().then((response) => {
                response.forEach((item) => {
                    const div = document.createElement("div");
                    div.textContent = item.name;
                    div.classList.add("item");
                    container.appendChild(div);
                });
            });
        })
        .catch((e) => { });
};
  
const debounce = (fn, delay = 1000) => {
    let timerId = null;
    return (...args) => {
        clearTimeout(timerId);
        timerId = setTimeout(() => fn(...args), delay);
    };
};
  
const onInput = debounce(makeAPICall, 500);
  
input.addEventListener("input", (e) => {
    onInput(e.target.value);
});


Output:

Implement Search Box with debounce in javascript

Implement Search Box with debounce in javascript

Explanation: Because we had used debouncing technique hence on every input provided the API call is not being made, instead 500ms after we stop providing input, the API call is made.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads