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
OutputSearching 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.
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 cer
6 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
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
Timing Events in Javascript Timing events are the events that help to execute a piece of code at a specific time interval. These events are directly available in the HTML DOM (Document Object Model) Window object, i.e., they are present in the browser. So, these are called global methods and can be invoked through the 'window'
5 min read
JavaScript Events JavaScript Events are actions or occurrences that happen in the browser. They can be triggered by various user interactions or by the browser itself. HTML<html> <script> function myFun() { document.getElementById( "gfg").innerHTML = "GeeksforGeeks"; } </script> <body> <but
3 min read
How to write a function in JavaScript ? JavaScript functions serve as reusable blocks of code that can be called from anywhere within your application. They eliminate the need to repeat the same code, promoting code reusability and modularity. By breaking down a large program into smaller, manageable functions, programmers can enhance cod
4 min read