AI News Hub Logo

AI News Hub

What is Debouncing in JS?

DEV Community
Ashish Ghildiyal

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 🎯 Problem Debouncing Solves input typing πŸ‘‰ Example: 🎯 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 πŸ‘‰ 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 βœ… Function executes ONCE πŸ” What β€œDelay Until Last Event” Actually Means πŸ‘‰ Every new event: Resets the delay Prevents execution πŸ‘‰ Only when: No new events happen for delay time πŸ‘‰ Then function runs βš™οΈ Visual Timeline Typing: h e l l o Time: |---|---|---|---|---| Timer: reset reset reset reset β†’ execute 🧠 Core Logic (Important) Event happens ↓ Cancel previous execution ↓ Wait for delay ↓ If no new event β†’ execute πŸ’» 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); }; } πŸ”₯ Super Simple Analogy You’re waiting for someone to stop talking before replying. If they keep talking β†’ you wait πŸ‘‰ That’s debouncing