Implement Search Box with debounce in JavaScript Last Updated : 24 Jul, 2024 Comments Improve Suggest changes Like Article Like 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: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.ApproachWe 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: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. Comment More infoAdvertise with us Next Article Implement Search Box with debounce in JavaScript sakshi_srivastava Follow Improve Article Tags : HTML JavaScript-Questions Similar Reads How to set the cursor to wait in JavaScript ? In JavaScript, we could easily set the cursor to wait. In this article, we will see how we are going to do this. Actually, it's quite an easy task, there is a CSS cursor property and it has some values and one of the values is wait. We will use the [cursor: wait] property of CSS and control its beha 3 min read How to Simulate a Click in JavaScript? Simulating a click in JavaScript means triggering a click event on an HTML element using code, rather than requiring manual user interaction. This technique is useful for automating actions like clicking buttons, links, or other interactive elements, enhancing web functionality, and triggering hidde 3 min read How to Design a Custom Alert Box using JavaScript ? An alert box is a built-in feature in JavaScript that displays a small window with a message to the user. It's primarily used for providing information to the user, displaying warnings, or prompting the user for confirmation. The below approaches can be used to create a custom alert box in JavaScrip 4 min read How to Create a Modal Box using HTML CSS and JavaScript? We will learn how to create a modal dialog box using HTML, CSS, and JavaScript. A modal is a pop-up dialog that appears on top of the main content and requires the user to interact with it before returning to the main screen.Approach to Create Modal BoxHTML Structure:Create a button that opens the m 2 min read How to trigger HTML button after hitting enter button in textbox using JavaScript ? In this article, we are given an HTML document containing a text area and the task is to trigger the button when the user hit Enter button. We can do it by using the "keyup", "keydown", or "keypress" event listener on the textbox depending on the need. When this event is triggered, we check if the k 4 min read Design a Letter Hover Effect using HTML CSS and JavaScript In this article, we will learn to implement the bouncing letter hover effect using simple HTML, CSS, and JavaScript. HTML is used to create the structure of the page, CSS is used to set the styling and JavaScript is used for animation. Approach to Create the Bouncing Letter Hover EffectHTML Code: To 2 min read jQuery UI Bounce Effect In this article, we are going to show the effect of bounce using jQuery UI. All the content will show the bounce effect when the action button is clicked which actually triggers the bounce effect script. Syntax : $( ".selector" ).effect( selectedEffect, options, time(in ms), callback ); Parameters: 2 min read How to make your own countUp.js plugin using JavaScript ? prerequisite: Document Object Model ( DOM )Â Use of Classes in ES6 If you are a beginner in JavaScript and have basic programming knowledge then don't worry, you have landed in a perfect place. Let us divide the problem into multiple segments: Implementing a simple structure using HTML.Providing a ba 2 min read How to add fade-out effect using pure JavaScript ? The fade effect is described as the gradual increase and decrease in the opacity of the selected portion. In other words, the fade effect is termed as the increase and decrease in opacity with respect to time. When this effect is applied with a gradual decrease in the opacity it is known as the fade 4 min read How to make a key fire when key is pressed using JavaScript ? In JavaScript, holding down a key will fire the key continuously until it is released. This behavior may be used in applications such as games where a key may be expected to fire only once even after being held down. This can be achieved using two methods: Method 1: Using a flag variable to check th 3 min read Like