Skip to content

Instantly share code, notes, and snippets.

@griimick
Last active April 13, 2021 07:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save griimick/2d8f5f12e27eef95f6ae28d5c0247911 to your computer and use it in GitHub Desktop.
Save griimick/2d8f5f12e27eef95f6ae28d5c0247911 to your computer and use it in GitHub Desktop.
Debounce & Throttle
/*
* 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);
};
}
/*
* 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);
}
}
}
@griimick
Copy link
Author

griimick commented Apr 13, 2021

@griimick
Copy link
Author

Lodash implements Throttle using their Debounce implementation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment