Skip to content

Instantly share code, notes, and snippets.

@brandonhimpfen
Created January 2, 2026 08:58
Show Gist options
  • Select an option

  • Save brandonhimpfen/eb31f6750fb00c0370c62885024cbf11 to your computer and use it in GitHub Desktop.

Select an option

Save brandonhimpfen/eb31f6750fb00c0370c62885024cbf11 to your computer and use it in GitHub Desktop.
A simple, dependency-free JavaScript debounce utility for limiting how often a function executes.
/**
* debounce(fn, wait)
*
* Delays invoking `fn` until after `wait` milliseconds have elapsed
* since the last time the debounced function was called.
*
* Common use cases:
* - Resize events
* - Scroll handlers
* - Input / search fields
*
* @param {Function} fn Function to debounce
* @param {number} wait Delay in milliseconds
* @returns {Function} Debounced function
*/
function debounce(fn, wait = 300) {
let timeoutId;
return function (...args) {
const context = this;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
fn.apply(context, args);
}, wait);
};
}
/* ---------------------------------------------------------------------------
* Example usage
* ---------------------------------------------------------------------------
*
* Debounce is useful when you want to limit how often a function runs,
* especially for events that fire frequently (resize, scroll, input).
*
* In this example, `handleResize` will only run once the user has stopped
* resizing the window for 250ms.
*
* ------------------------------------------------------------------------- */
const handleResize = debounce(() => {
console.log('Window resized');
}, 250);
window.addEventListener('resize', handleResize);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment