Skip to content

Instantly share code, notes, and snippets.

@yuriy-o
Last active November 23, 2022 08:40
Show Gist options
  • Save yuriy-o/afe53cc174fe510fff3f7d2176c4dd60 to your computer and use it in GitHub Desktop.
Save yuriy-o/afe53cc174fe510fff3f7d2176c4dd60 to your computer and use it in GitHub Desktop.
throttle & debounce function
/**
* Creates a throttled function that only invokes _throttledFunc_ at most once per every _timeout_ milliseconds
* https://youtu.be/9jtfYW6o1PE?t=4593
*
* @param {Function} throttledFunc
* @param {number} timeout
*
* @returns {Function}
*/
function throttle(throttledFunc, timeout) {
let isTriggerAllowed = true;
let lastTriggeredCall = null;
setInterval(() => {
if (lastTriggeredCall) {
lastTriggeredCall();
}
isTriggerAllowed = true;
}, timeout);
return (...args) => {
if (isTriggerAllowed) {
isTriggerAllowed = false;
lastTriggeredCall = null;
throttledFunc(...args);
} else {
lastTriggeredCall = () => throttledFunc(...args);
}
};
}
/**
* Creates a debounced function that delays invoking _debouncedFunc_ until after _timeout_ milliseconds
* have elapsed since the last time the debounced function was invoked
*
* @param {Function} debouncedFunc
* @param {number} timeout
*
* @returns {Function}
*/
function debounce(debouncedFunc, timeout) {
let timerRef = 0;
return (...args) => {
clearTimeout(timerRef);
timerRef = setTimeout(() => {
debouncedFunc(...args);
}, timeout);
};
}
export { debounce, throttle };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment