Debounce
Debounce
Section titled “Debounce”Introduction
Section titled “Introduction”Debounce delays function execution until after a specified pause in events. It’s like saying “wait until they stop typing, then search.”
How It Works
Section titled “How It Works”flowchart TD A["Rapid events: |||||||||"] A --> B["Debounce: Wait for pause"] B --> B1[" | |"] B1 --> B2["Executes ONCE after pause"]Basic Implementation
Section titled “Basic Implementation”function debounce(fn, delay) { let timeoutId;
return function(...args) { clearTimeout(timeoutId); timeoutId = setTimeout(() => { fn.apply(this, args); }, delay); };}
// Usage: Search inputconst searchInput = document.getElementById('search');searchInput.addEventListener('input', debounce(async (e) => { const results = await fetch(`/api/search?q=${e.target.value}`); displayResults(results);}, 300));How It Works Step by Step
Section titled “How It Works Step by Step”- User types ‘h’ → timer starts (300ms)
- User types ‘he’ → previous timer cleared, new timer starts
- User types ‘hel’ → previous timer cleared, new timer starts
- User stops typing → 300ms passes → function executes once
Summary
Section titled “Summary”- Delays execution until events stop for a specified time
- Perfect for search inputs, form validation
- Only the final call matters