Introduction
Debounce Function in JavaScript is a common utility that helps improve performance by limiting how often a function can be triggered. If you’ve ever faced issues like firing too many API calls on keypress or scroll events, debounce is your solution.
How to Write a Debounce Function in JavaScript
Below is a simple example of how to create a reusable debounce function for any project:
function debounce(func, delay) {
let timeoutId;
return function(…args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
// Usage:
const debouncedLog = debounce(() => console.log(‘Action triggered!’), 300);
window.addEventListener(‘resize’, debouncedLog);
How This Works
The Debounce Function in JavaScript works by clearing any previously scheduled function call until the user stops triggering the event for a set delay time. It’s perfect for resize, input, and scroll events.
Why Use This?
Debounce Function in JavaScript helps you reduce unnecessary function executions and can improve your app’s responsiveness, especially during high-frequency events.
Common Mistake
A common mistake is placing the debounce function inside another function unnecessarily, which creates multiple new debounce handlers instead of reusing one.
Pro Tip
Combine this with throttling when you want to control both minimum and maximum frequencies for event triggers.