close

DEV Community

Ashish Ghildiyal
Ashish Ghildiyal

Posted on

What is Debouncing in JS?

debouncing is a technique to:

Delay the execution of a function until a certain time has passed since the last event

🧠 Simple Meaning

πŸ‘‰ Don’t run the function immediately
πŸ‘‰ Wait for the user to stop triggering events
πŸ‘‰ Then run the function once

🎯 Problem Debouncing Solves
Some events fire very frequently:

input typing
scroll
resize
mousemove

πŸ‘‰ Example:
If a user types β€œhello”, an API call might fire 5 times ❌

🎯 Real-Life Example (Typing)

Imagine a search box:

User types:

h β†’ e β†’ l β†’ l β†’ o

Each keypress is an event

❌ Without Delay

h β†’ API call  
e β†’ API call  
l β†’ API call  
l β†’ API call  
o β†’ API call  
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ 5 calls (wasteful ❌)

βœ… With Debouncing (Delay Applied)

Let’s say delay = 500ms

Step-by-step:


1. User types β€œh”
Start timer (500ms)

2. User types β€œe” before 500ms
Cancel previous timer ❌  
Start new timer

3. User types β€œl”
Cancel again ❌  
Start new timer

4. User stops typing
No more events β†’ timer completes βœ…  
Enter fullscreen mode Exit fullscreen mode

Function executes ONCE

πŸ” What β€œDelay Until Last Event” Actually Means

πŸ‘‰ Every new event:

Resets the delay
Prevents execution
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Only when:

No new events happen for delay time
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Then function runs

βš™οΈ Visual Timeline

Typing:   h   e   l   l   o
Time:     |---|---|---|---|---|

Timer:    reset reset reset reset β†’ execute
Enter fullscreen mode Exit fullscreen mode

🧠 Core Logic (Important)

Event happens
   ↓
Cancel previous execution
   ↓
Wait for delay
   ↓
If no new event β†’ execute
Enter fullscreen mode Exit fullscreen mode

πŸ’» Code to Understand It

function debounce(fn, delay) {
  let timer;

  return function (...args) {
    clearTimeout(timer); // cancel previous

    timer = setTimeout(() => {
      fn(...args); // run after delay
    }, delay);
  };
}
Enter fullscreen mode Exit fullscreen mode

Usage

const handleInput = debounce((e) => {
  console.log("API call:", e.target.value);
}, 500);

input.addEventListener("input", handleInput);

Enter fullscreen mode Exit fullscreen mode

πŸ”₯ Super Simple Analogy

You’re waiting for someone to stop talking before replying.

If they keep talking β†’ you wait
When they stop β†’ you respond

πŸ‘‰ That’s debouncing

Top comments (0)