Learn the concept
Debouncing & Throttling
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)} />;
}By debouncing the input event, API calls are only made after the user stops typing for a short period, reducing unnecessary requests and server load.
By throttling updates to charts or graphs that respond to continuous data streams (e.g., websocket events), ensuring that UI updates occur at a manageable rate and maintain responsiveness.
By debouncing the resize event, complex layout recalculations are only performed once the user finishes resizing the window, preventing janky performance during the resize operation.
Implement a search input field that uses a debounce function to delay API calls until the user has paused typing.
Create a scroll-triggered progress bar or parallax effect that updates its position/animation using a throttled scroll event listener to maintain smooth performance.
Google's search bar utilizes debouncing to efficiently handle user input, triggering search suggestions or results only after a brief pause in typing, optimizing API usage and responsiveness.
Twitter employs throttling for various interactive elements, such as updating the 'like' count or refreshing timelines, to manage network requests and UI rendering efficiently during continuous user activity (e.g., rapid scrolling).