Created
August 13, 2022 18:02
-
-
Save jgoslow/cf092a2f2b9ac093cc4486348b473363 to your computer and use it in GitHub Desktop.
Throttle and Debounce JS Functions
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 | |
* to reduce # of events fired | |
* example: Scroll listeners | |
*/ | |
function debounce(callback, interval) { | |
let debounceTimeoutId; | |
return function(...args) { | |
clearTimeout(debounceTimeoutId); | |
debounceTimeoutId = setTimeout(() => callback.apply(this, args), interval); | |
}; | |
} |
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
/** | |
* Throttling Function | |
* to reduce # of events fired | |
* example: Scroll listeners | |
*/ | |
function throttle(callback, interval) { | |
let enableCall = true; | |
return function(...args) { | |
if (!enableCall) return; | |
enableCall = false; | |
callback.apply(this, args); | |
setTimeout(() => enableCall = true, interval); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment