JavaScript Debouncing
Debouncing is a way to make sure a function only runs after an action has stopped happening for a certain amount of time. Debouncing is about waiting for a pause before taking action.
Why to use: making apps faster, smoother, and more efficient.
Example: Search Suggestions — Debounce ensures the request is sent only after the user stops typing, reducing server load.
Get Tech Mentor’s stories in your inbox
Join Medium for free to get updates from this writer.
When to use it:
- Typing in search bars, autocomplete suggestions
- Form Validations — validate after user stops typing
- Filter or Sorting on UI
- To reduce unnecessary API Calls
- Auto Save
JavaScript Sample Code : To validate use input, runs 500ms after the user stops typing, reducing unnecessary checks.
//debounce function call, will run after given delay
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer); // clear previous timer
timer = setTimeout(() => {
fn.apply(this, args); // run function after delay
}, delay);
};
}
// vlidation function
function validateUsername() {
const username = document.getElementById("username").value.trim();
if (username.length < 5) {
throw new Error("Username must be at least 5 characters");
}
return true;
}
//Call debounce function on user name input validation
document.getElementById("username").addEventListener("input", debounce(validateUsername, 500));
Conclusion: The main idea is to apply debouncing whenever possible to minimize unnecessary function calls and ensure a smoother user experience.







