Skip to content

Instantly share code, notes, and snippets.

@jll90
Created February 13, 2020 14:55
Show Gist options
  • Save jll90/fb3f4c331f7181404cb331cd2daa15e5 to your computer and use it in GitHub Desktop.
Save jll90/fb3f4c331f7181404cb331cd2daa15e5 to your computer and use it in GitHub Desktop.
JavaScript Throttle & Debounce Comparison
const throttle = (func, limit) => {
let engaged = false;
return function () {
const args = arguments;
const context = this;
if (!engaged) {
func.apply(context, args);
engaged = true;
setTimeout(() => engaged = false, limit);
}
}
}
const debounce = (func, delay) => {
let engaged = null;
return function () {
const args = arguments;
const context = this;
clearTimeout(engaged);
engaged = setTimeout(() => func.apply(context, args), delay)
}
}
const testThrottle = () => {
console.log('throttle');
}
const testDebounce = () => {
console.log('debounce');
}
const throttledFn = throttle(testThrottle, 500);
const debouncedFn = debounce(testDebounce, 1000);
throttledFn();
throttledFn(1);
setTimeout(() => throttledFn(), 600);
setTimeout(() => throttledFn(), 700);
const debounceInterval = setInterval(() => debouncedFn(), 950);
setTimeout(() => {
clearInterval(debounceInterval);
}, 10000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment