Sitemap
JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

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:

  1. Typing in search bars, autocomplete suggestions
  2. Form Validations — validate after user stops typing
  3. Filter or Sorting on UI
  4. To reduce unnecessary API Calls
  5. 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.

--

--

Tech Mentor
Tech Mentor

Written by Tech Mentor

Turning technology concepts into clear writing. Writing about systems design, JavaScript, Java, and web technologies.

JavaScript in Plain English
JavaScript in Plain English

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.