Created
March 12, 2026 06:35
-
-
Save av1v3k/ac43ac41f2cf4cca63716fb496a4ee26 to your computer and use it in GitHub Desktop.
Debounce & Throttle
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
| /*Debounce Function*/ | |
| //================== | |
| /*Wait for the "quiet" moment.*/ | |
| function debounce(func, delay) { | |
| let timeoutId; | |
| return function(...args) { | |
| clearTimeout(timeoutId); // Reset the clock every time | |
| timeoutId = setTimeout(() => { | |
| func.apply(this, args); | |
| }, delay); | |
| }; | |
| } | |
| /*Throttle Function*/ | |
| //================== | |
| /*Force a "speed limit"*/ | |
| function throttle(func, limit) { | |
| let inThrottle; | |
| return function(...args) { | |
| if (!inThrottle) { | |
| func.apply(this, args); // Run the function immediately | |
| inThrottle = true; // Lock it | |
| setTimeout(() => inThrottle = false, limit); // Unlock after time passes | |
| } | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment