Skip to content

Instantly share code, notes, and snippets.

@georg3103
Last active April 15, 2019 00:08
Show Gist options
  • Save georg3103/c9816844ee15debe8dc0b7882f6ce8ab to your computer and use it in GitHub Desktop.
Save georg3103/c9816844ee15debe8dc0b7882f6ce8ab to your computer and use it in GitHub Desktop.
Helper Functions
export function throttle(func, ms) {
let isThrottled = false,
savedArgs,
savedThis;
function wrapper(...args) {
// memorize all func calls
if (isThrottled) {
savedArgs = args;
savedThis = this;
return;
}
func.apply(this, args);
isThrottled = true;
setTimeout(function() {
isThrottled = false;
// the last func call will work after timeout
if (savedArgs) {
wrapper.apply(savedThis, savedArgs);
savedArgs = savedThis = null;
}
}, ms);
}
return wrapper;
}
export function debounce(func, ms) {
let timer = null;
return function (...args) {
const onComplete = () => {
func.apply(this, args);
timer = null;
}
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(onComplete, ms);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment