In modern web applications, user experience matters. A responsive and smooth UI not only feels good — it performs better. But what happens when a user types too fast, scrolls endlessly, or resizes a window like crazy? That’s where debouncing comes in.
In this post, you’ll learn:
debounce
function in JavaScriptDebounce is a technique used to limit how often a function is called. Specifically, it ensures a function only executes after a certain amount of time has passed since it was last invoked.
Think of it like this:
“Wait until the user is done typing before sending the API request.”
Here are some common scenarios where debouncing improves performance and UX:
Let’s build our own debounce
function step-by-step.
function debounce(fn, delay) {let timeoutId;return function (...args) {clearTimeout(timeoutId);timeoutId = setTimeout(() => {fn(...args);}, delay);};}
delay
ms.this
Context (Advanced Version)If the original function uses this
(like in class methods), we need to preserve the context.
function debounce(fn, delay) {let timeoutId;return function (...args) {const context = this;clearTimeout(timeoutId);timeoutId = setTimeout(() => {fn.apply(context, args);}, delay);};}
const logInput = debounce((value) => {console.log("Searching for:", value);}, 500);// Simulate user typinglogInput("r");logInput("re");logInput("rea");logInput("reac");logInput("react"); // ← Only this logs after 500ms
Perfect for live search fields — only the last input triggers the API.
_.debounce
in large projects for reliability.Feature | Debounce | Throttle |
---|---|---|
Use case | Wait until user stops doing something | Run function at regular intervals |
Example | Search input | Scroll tracking, mouse movement |
Debounce is one of those small, elegant solutions that makes a huge difference in your frontend projects. Whether you’re building a search bar or handling resize events, mastering debounce can help you create smoother, faster, and more efficient web apps.
Want to take it further? Try building a custom useDebounce
React hook — or ask me, and I’ll help you write one too!
Let me know if you want this formatted for a blog platform like Dev.to, Medium, or Markdown for your portfolio.
Quick Links
Legal Stuff
Social Media