Last active
April 13, 2021 07:02
-
-
Save griimick/2d8f5f12e27eef95f6ae28d5c0247911 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
/* | |
* Call dembounced function only after `limit` amount of time | |
* has passed since the last call. The limit resets if the function is called | |
* before before `limit` amount of duraction has passed from the last call. | |
* This impliesa delay between the last event and handle function call. | |
*/ | |
export default customDebounce (func, limit) { | |
let timeout; | |
return debouncedFunction () { | |
let context = this, args = arguments; | |
const effect = () => { | |
timeout = null; | |
func.apply(context, args); | |
}; | |
clearTimeout(timeout); | |
timeout = setTimeout(effect, limit); | |
}; | |
} |
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
/* | |
* Call throttled function only once per `limit` amount of time. | |
* Every other call in between is rejected or ignored. | |
*/ | |
export default customThrottle (func, limit) { | |
let flag = true; | |
return function throttledFunc () { | |
let context = this, args = arguments; | |
if (flag) { | |
func.apply(context, args); | |
flag = false; | |
setTimeout(() => { | |
flag = true; | |
}, limit); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Lodash implements Throttle using their Debounce implementation.