In frontend development, we often encounter events that are triggered frequently, such as input in search boxes, window resizing, scroll events, and more. If not handled properly, these can lead to performance issues.
Debounce and Throttle are two essential techniques to solve such problems.
What is Debounce?
Debounce means: within a certain period, only the last call to a function is executed after the event stops firing.
Use Cases
- Search input
- Window resizing
- Form validation
Code Implementation
function debounce<T extends (...args: any[]) => any>(
func: T,
wait: number
): (...args: Parameters<T>) => void {
let timeout: NodeJS.Timeout;
return function (...args: Parameters<T>) {
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(this, args);
}, wait);
};
}
// Example usage
const handleSearch = debounce((query: string) => {
console.log('Searching for:', query);
}, 300);
What is Throttle?
Throttle means: within a certain period, multiple calls to a function only execute once at the beginning of that period.
Use Cases
- Scroll event handling
- Keyboard input in games
- Drag-and-drop actions
Code Implementation
function throttle<T extends (...args: any[]) => any>(
func: T,
wait: number
): (...args: Parameters<T>) => void {
let lastCall = 0;
return function (...args: Parameters<T>) {
const now = Date.now();
if (now - lastCall >= wait) {
func.apply(this, args);
lastCall = now;
}
};
}
// Example usage
const handleScroll = throttle(() => {
console.log('Scrolling...');
}, 200);
Main Differences
-
Execution Timing
- Debounce: Executes after the user stops performing the action
- Throttle: Executes at a fixed time interval
-
Use Cases
- Debounce: Best for events like input where you wait for user to finish
- Throttle: Best for continuous events like scroll or resize
-
Effect
- Debounce: Merges multiple triggers into one
- Throttle: Ensures one execution in a given timeframe
Practical Examples
Debounce in Search Box
const searchInput = document.querySelector('input');
searchInput.addEventListener('input', debounce((e) => {
// Trigger search request
searchAPI(e.target.value);
}, 300));
Throttle for Scroll Events
window.addEventListener('scroll', throttle(() => {
// Handle scroll update
updateScrollPosition();
}, 100));
Recommendation
- Use debounce if you want to wait for the user to finish the action
- Use throttle if you want to ensure the function runs once in a set period
- Use throttle for very frequent triggers
- Use debounce for actions that depend on user completion
Conclusion
Debounce and Throttle are powerful techniques for frontend performance optimization. They help control function execution frequency and enhance user experience.
Remember:
- Debounce: Wait for user to finish
- Throttle: Ensure execution frequency
Choose wisely and elevate your app's performance!