Table of contentsClick link to navigate to the desired location
This content has been automatically translated from Ukrainian.
If you have ever worked with events in JavaScript, such as scroll, resize, or keyup, you have probably noticed that they can be triggered very frequently. For example, when typing in a search field, the keyup event may fire after each key press. This can create unnecessary load on the browser or server, especially if each call makes an API request.
To avoid such problems, debounce is used — a technique that limits the frequency of function calls by delaying its execution until the event stops firing for a specified amount of time.
How does debounce work?
The idea is simple: when the event is triggered, we delay the execution of the function for a certain period of time. If the event is triggered again before this time is up, the timer is reset and the countdown starts over. Only when the event stops does the function execute.
Debounce example in JavaScript
function debounce(func, delay) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), delay);
};
}
// Using debounce to handle text input event
const input = document.querySelector("#search");
const handleInput = (event) => {
console.log("Search: ", event.target.value);
};
input.addEventListener("keyup", debounce(handleInput, 500));
In this example, each input in the search field resets the timer, and only after 500ms without new input does handleInput execute.
Where to use debounce?
- Search queries — to avoid sending requests to the server on every key press.
- Window resize handling — to avoid overloading the browser with calculations.
- Scroll event listeners — for example, to load new content on scroll (infinite scroll).
- Auto-saving forms — to save data only after input is complete.
- Form validation - for example, to check for available usernames.
Debounce helps optimize performance by reducing the number of function calls that are frequently triggered. This is especially useful when dealing with frequent events such as text input, scrolling, or window resizing. By using debounce, you can improve user interaction and reduce system load.
This post doesn't have any additions from the author yet.