Debounce Function
When handling user input like window resizing or key presses, it’s easy to overwhelm your app with rapid successive function calls. A debounce utility delays execution until there’s a pause, making interactions smoother and preventing unnecessary work. I use this snippet in search boxes, scroll event handlers, and any situation where a little breathing room improves the user experience.
Here’s a simple debounce implementation in JavaScript. It takes a function fn
and a delay in milliseconds, returning a new function that schedules execution. If the returned function is called again before the delay expires, the timer resets. Use it like this: const debounced = debounce(doSearch, 300);
and wire it to your event listener.
export function debounce(fn, delay = 300) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
This utility is tiny but powerful; drop it into your toolkit whenever you need to limit the rate of function calls without losing responsiveness.