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 π― 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
