javascript 📝 Code Snippet
JavaScript Debounce Function
Efficient debounce implementation for rate-limiting function execution
Language: javascript • Intermediate
• Updated: February 12, 2026
A debounce function limits how often a function can be called. It’s useful for performance optimization when handling events like scrolling, resizing, or typing.
Usage
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
// Example usage
const handleResize = debounce(() => {
console.log('Window resized!');
}, 250);
window.addEventListener('resize', handleResize);
How It Works
- The debounce function returns a new function that wraps your original function
- When called, it sets a timer to execute your function after the specified wait time
- If called again before the timer expires, it cancels the previous timer and sets a new one
- This ensures your function only runs after the user has stopped triggering the event
Common Use Cases
- Search input fields (wait until user stops typing)
- Window resize handlers
- Scroll event listeners
- Form validation
- API request throttling