Skip to content

Instantly share code, notes, and snippets.

@maxam2017
Created September 27, 2023 17:36
Show Gist options
  • Save maxam2017/bdb9cee08c27a00f23073586a7016532 to your computer and use it in GitHub Desktop.
Save maxam2017/bdb9cee08c27a00f23073586a7016532 to your computer and use it in GitHub Desktop.
Debounce & Throttle
function debounce(fn, wait) {
let timerId;
return function debounced(...args) {
clearTimeout(timerId);
const that = this;
timerId = setTimeout(() => fn.apply(that, args), wait);
};
}
function throttle(fn, wait) {
let shouldThrottle = false;
return function throttled(...args) {
if (shouldThrottle) return;
shouldThrottle = true;
setTimeout(() => {
shouldThrottle = false;
}, wait);
fn.apply(this, args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment