Created
September 13, 2024 02:28
-
-
Save ardislu/ffe76e69026bebba257f713aab50c5dd to your computer and use it in GitHub Desktop.
Minimal debounce function and example in JavaScript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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