Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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:
Debugging 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
Debugging in JavaScript

J

JayantaTalukdar
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • 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
  • Code Golfing in JavaScript
    Code Golf in JavaScript refers to attempting a problem to solve using the least amount of characters possible. Like in Golf, the low score wins, the fewest amount of characters "wins". JavaScript is a fantastic language for code golfing due to backward compatibility, quirks, it is being a high-level
    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 ce
    6 min read
  • JavaScript get Function
    JavaScript get function is used to access the properties of an object using dot notation or square brackets. It allows you to retrieve the value associated with a particular property key and the get function is often used when working with objects that implement JavaScript's getter function. The get
    3 min read
  • JavaScript eval() Function
    The eval() function in JavaScript is a powerful but potentially dangerous feature that allows the execution of JavaScript code stored in a string. While eval() can be useful in some cases, its use is generally discouraged due to security risks and performance concerns. Executing JavaScript Code with
    3 min read
  • How to debug JavaScript File ?
    Debugging is essential because there are many errors that are not giving any kind of messages so to find out that we debug the code and find out the missing point. Example 1:  Using console.log() Method In this, we can find out the error by consoling the code in various places. Using a console is on
    2 min read
  • Array of functions in JavaScript
    Given an array containing functions and the task is to access its element in different ways using JavaScript. Approach: Declare an array of functions.The array of functions works with indexes like an array function. Example 1: In this example, the function call is initiated from the element of the a
    2 min read
  • JavaScript if-else
    JavaScript if-else statement executes a block of code based on a condition. If the condition evaluates to true, the code inside the "if" block executes; otherwise, the code inside the "else" block, if present, executes. Such control statements are used to cause the flow of execution to advance and b
    4 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. Here are some inter
    5 min read
  • Event Queue in JavaScript
    JavaScript, being single-threaded, processes tasks sequentially, meaning it executes one task at a time. This can pose a challenge when dealing with operations that take time to complete, such as fetching data from a server or performing complex calculations. To handle such scenarios efficiently, Ja
    5 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