Skip to content

Instantly share code, notes, and snippets.

@kashyapkaki
Created May 23, 2025 15:10
Show Gist options
  • Save kashyapkaki/76c9532c96ac6cbd90908436917bf63c to your computer and use it in GitHub Desktop.
Save kashyapkaki/76c9532c96ac6cbd90908436917bf63c to your computer and use it in GitHub Desktop.
A lightweight debounce function to delay execution of a given callback until after a specified delay in milliseconds. Commonly used in scroll, resize, search input, or canvas-related event handling to avoid performance issues from rapid firing.
// Debounce function to limit how often a function is executed
function debounce(fn, delay) {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
}
// Usage
window.addEventListener('resize', debounce(() => {
console.log('Window resized!');
}, 300));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment