Skip to content

Instantly share code, notes, and snippets.

@A-Ostrovnyy
Last active June 13, 2021 12:59
Show Gist options
  • Save A-Ostrovnyy/df5bd275040a10610d629a474a0b5bb2 to your computer and use it in GitHub Desktop.
Save A-Ostrovnyy/df5bd275040a10610d629a474a0b5bb2 to your computer and use it in GitHub Desktop.
Helpers
function debounce(fn, ms) {
let timeout;
return function() {
const fnCall = () => fn.apply(this, arguments)
clearTimeout(timeout);
timeout = setTimeout(fnCall, ms);
}
}
const debounce = (fn: Func, ms = 300) => {
let timeoutId: ReturnType<typeof setTimeout>;
return function (this: any, ...args: any[]) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn.apply(this, args), ms);
};
};
function throttle(fn, ms) {
let isThrottled = false;
let savedArgs;
let savedThis;
function wrapper() {
if (isThrottled) {
savedArgs = arguments;
savedThis = this;
return
}
fn.apply(this, arguments);
isThrottled = true;
setTimeout(function() {
isThrottled = false;
if (savedArgs) {
wrapper.apply(savedThis, savedArgs);
savedArgs = savedThis = null;
}
}, ms)
}
return wrapper
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment