Last active
April 15, 2019 00:08
-
-
Save georg3103/c9816844ee15debe8dc0b7882f6ce8ab to your computer and use it in GitHub Desktop.
Helper Functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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