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
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Debouncing in JavaScript
Next article icon

Debouncing in JavaScript

Last Updated : 15 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, debouncing is a technique used to ensure that a function is not called too frequently. It is commonly used in scenarios where events are triggered rapidly, such as typing in an input field or resizing a window. Without debouncing, functions might be executed many times in quick succession, causing performance issues or unwanted behaviour.

What is Debouncing in JavaScript?

Debouncing in JavaScript can be defined as the technique that is used to limit the number of times a function gets executed. Debouncing is useful when the event is frequently being triggered in a short interval of time like typing, scrolling, and resizing.

  • Limit Function Calls: During frequent events like typing, resizing, or scrolling debouncing prevents the frequent function calls.
  • Delays Execution: After the specific delay only the function is executed, ensuring no rapid consecutive calls.
  • Prevents Overload: Efficiently managing high-frequency triggers helps in preventing overloading.
JavaScript
// Debounce function function debounce(func, delay) {     let timeout;     return function (...args) {         clearTimeout(timeout);         timeout = setTimeout(() => {             func.apply(this, args);         }, delay);     }; }  // Function to be debounced function search(query) {     console.log('Searching for:', query); }  // Create a debounced version of the search function const dSearch = debounce(search, 100);  // Simulate typing with multiple calls to the debounced function dSearch('Hello'); dSearch('Hello, '); dSearch('Hello, World!');  // Only this call will trigger after 100ms 

Output
Searching for: Hello, World! 

In this example

  • debounce() function: It is the higher order function that takes (delay) and function(func) as the arguments. It returns a new function that will wait for the specified delay before calling the original function.
  • clearTimeout(): It is used to clear any previous set timeout so that if the event is triggered repeatedly the function call does not happen too quickly.
  • setTimeout(): This method is used to set the timeout after clearing the previous timeouts.
  • Search function: It is the placeholder for the function we want to debounce.

How Does Debouncing Work?

In JavaScript the debouncing function works when the event is being triggered. The Debounce wait for the specific period to run the function, it doesn't run the function immediately. If before the wait time is over, the event is triggered again then the previous function call is canceled and it resets the timer. Once the timer completes without any further event triggers, the function is executed. This ensures that the function is executed only after the event stops occurring for a specific period.

Use Cases for Debouncing in JavaScript

The use cases of the debouncing in javaScript are mentioned below:

  • Search Input Field: In the search bar, the user types characters one after another due to which for each key press an API request is triggered. Debouncing makes sure that the API request is only sent when the user has finished typing.
let timer; document.getElementById("searchInput").addEventListener("input", () => {     clearTimeout(timer);     timer = setTimeout(() => console.log("Searching..."), 300); });
  • Window Resizing: When we resize the window browser, in a short interval of time the resize event gets fired multiple times. Debouncing can be used in handling this event.
let timer; window.addEventListener("resize", () => {     clearTimeout(timer);     timer = setTimeout(() => console.log("Window resized"), 500); });
  • Scroll Events: When the user scrolls the webpage the scroll event is triggered multiple times per second. By debouncing the event, the scroll handler function is executed only after the user has stopped scrolling for a specific duration.
let timer; window.addEventListener("scroll", () => {     clearTimeout(timer);     timer = setTimeout(() => console.log("Scrolling stopped"), 300); });
  • Form Validation: If in real-time we are validating a form as the user types, debouncing can be used to ensure that for every keystroke the validation function is not repeatedly triggered.
let timer;
document.getElementById("formInput").addEventListener("input", () => {
clearTimeout(timer);
timer = setTimeout(() => console.log("Validating..."), 500);
});

Benefits of Debouncing

  • Improved Performance: Debouncing helps in optimizing the performance by reducing the number of times of function execution, especially when we are handling frequent events like type. This reduces unnecessary resource usage.
  • Better User Experience: When the events are rapidly triggered then also the application remains responsive with debouncing.
  • Prevents Redundant API Calls: Debouncing ensures that the API requests are only sent when the user stops interacting with the page for a specific time. This helps the server from crashing with repeated requests.

Debouncing vs Throttling

Debouncing and Throttling both are used for limiting the function calls during an event, but they both work in different ways:

  • Debouncing: In Debouncing the function is called only when the event stops occurring for a specific time.
  • Throttling: In throttling at regular intervals the function is called (every 100ms), even if the event has occurred multiple times during that duration.

Features

Debouncing

Throttling

Definition

Executes a function only after a specified delay with no further events during that time.

Executes a function at regular intervals, no matter how frequently the event occurs.

Execution Trigger

After the event stops firing for a set time.

At fixed intervals, regardless of the event frequency.

Delay/Interval

Delays the function call until the event stops.

Limits the function call to a specific interval, regardless of continuous events.

Function Calls

The function is called once after the event stops firing for a defined time.

The function is called every X milliseconds, even if the event triggers more frequently.

Example

Typing in a search box

Scroll event

When to Use Debouncing

We can use the debouncing in the following conditions:

  • When we are dealing with operations like API calls then we can prevent unnecessary network requests to optimize the performance.
  • We can prevent the lags or delays due to repeated function execution to improve the user experience.
  • We can limit the function calls triggered by frequent user actions such as typing, and crolling.

Next Article
Debouncing in JavaScript

J

JayantaTalukdar
Improve
Article Tags :
  • Experienced
  • Computer Subject
  • CS – Placements
  • JavaScript
  • Web Technologies
  • Experiences
  • javascript-basics

Similar Reads

    Debugging in JavaScript
    Debugging is the process of testing, finding, and reducing bugs (errors) in computer programs. It involves:Identifying errors (syntax, runtime, or logical errors).Using debugging tools to analyze code execution.Implementing fixes and verifying correctness.Types of Errors in JavaScriptSyntax Errors:
    4 min read
    Dequeue in JavaScript
    A Deque (Double-Ended Queue) in JavaScript is a flexible data structure that functions like a horizontal container with both ends open, allowing data insertion and removal from both the front and the rear.Deques provide efficient access and modifications at both ends, reducing time complexity in cer
    6 min read
    Interesting Facts About JavaScript
    JavaScript (often abbreviated as JS) is one of the most popular programming languages in the world. It is an interpreted, high-level programming language that follows ECMAScript. It powers interactive websites and is packed with amazing features that make it special and powerful. Interesting Facts A
    5 min read
    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
    3 min read
    JavaScript Basics
    JavaScript is a versatile, lightweight scripting language widely used in web development. It can be utilized for both client-side and server-side development, making it essential for modern web applications. Known as the scripting language for web pages, JavaScript supports variables, data types, op
    6 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