JavaScriptMay 18, 2024 · 6 min read
JavaScript Debouncing Explained
Improve performance and optimize event handling in your JavaScript applications.
E
Evan Emran
Mobile Developer & Tech Blogger
What is Debouncing?
Debouncing ensures that a function is only executed after a certain amount of time has passed since it was last called. It is perfect for search inputs, resize handlers, and scroll events.
A Simple Implementation
function debounce(fn, delay = 300) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
Using It
const onSearch = debounce((query) => {
fetch(`/api/search?q=${query}`);
}, 400);
input.addEventListener('input', (e) => onSearch(e.target.value));
Debounce vs Throttle
- Debounce: waits for a pause in events.
- Throttle: runs at most once per interval.
Choose based on whether you care about the final value (debounce) or a steady cadence (throttle).