Debouncing waits until activity stops before executing (e.g., search after user stops typing). Throttling limits execution to once per interval during continuous activity (e.g., scroll events). Both reduce excessive function calls.
Debouncing:
Throttling:
Key Difference:
// Debounce implementation
function debounce(func, wait) {
let timeoutId;
return function executedFunction(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), wait);
};
}
// Usage: Search input
const searchInput = document.getElementById('search');
const search = debounce((query) => {
console.log('Searching for:', query);
fetch(`/api/search?q=${query}`);
}, 300);
searchInput.addEventListener('input', (e) => {
search(e.target.value);
});
// User types: h-e-l-l-o
// Only ONE search after user stops (300ms pause)
// React hook version
function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebouncedValue(value), delay);
return () => clearTimeout(timer);
}, [value, delay]);
return debouncedValue;
}
// Usage in React
function Search() {
const [query, setQuery] = useState('');
const debouncedQuery = useDebounce(query, 300);
useEffect(() => {
if (debouncedQuery) {
fetchResults(debouncedQuery);
}
}, [debouncedQuery]);
return <input value={query} onChange={e => setQuery(e.target.value)} />;
}