Open In App

Implement Search Box with debounce in JavaScript

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.






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




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;
}




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

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:




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




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;
}




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

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.


Article Tags :