Skip to content

Instantly share code, notes, and snippets.

@ardislu
Created September 13, 2024 02:28
Show Gist options
  • Select an option

  • Save ardislu/ffe76e69026bebba257f713aab50c5dd to your computer and use it in GitHub Desktop.

Select an option

Save ardislu/ffe76e69026bebba257f713aab50c5dd to your computer and use it in GitHub Desktop.
Minimal debounce function and example in JavaScript.
// Minimal debounce function:
function debounce(fn, wait) {
let timeoutId;
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn(...args), wait);
}
}
// Minified:
// const d=(f,w)=>{let t;return (...a)=>{clearTimeout(t);t=setTimeout(()=>f(...a),w)}}
// Example usage:
const handleMouse = e => console.log(`${e.clientX}, ${e.clientY}`); // Normal event handler
const handleMouseDebounced = debounce(handleMouse, 250);
document.addEventListener('mousemove', handleMouseDebounced); // Will only call handler after the mouse has stopped moving for 250ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment