Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • HTML Tutorial
  • HTML Exercises
  • HTML Tags
  • HTML Attributes
  • Global Attributes
  • Event Attributes
  • HTML Interview Questions
  • HTML DOM
  • DOM Audio/Video
  • HTML 5
  • HTML Examples
  • Color Picker
  • A to Z Guide
  • HTML Formatter
Open In App
Next Article:
Implement Search Box with debounce in JavaScript
Next article icon

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.

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:

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.


Next Article
Implement Search Box with debounce in JavaScript

S

sakshi_srivastava
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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences