Last active
September 17, 2018 14:55
-
-
Save oddvalue/7e7fd538762aa1d30325c12c4410fca4 to your computer and use it in GitHub Desktop.
Debounce
This file contains hidden or 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
/** | |
* Prevent regularly called functions (scroll/resize event listeners, etc..) from | |
* getting out of hand. | |
* | |
* @param {Function} callback Function to debounce | |
* @param {integer} wait Delay between function calls in ms | |
* @param {Objects} context Passed as `this` in debounced function | |
* @return {Function} debounced function | |
* | |
* @usage | |
* import debounce from './debounce'; | |
* const debounced = debounce(() => { | |
* ... | |
* }); | |
* window.addEventListener('scroll', debounced, { passive: true }); | |
*/ | |
export default (callback, wait, context = this) => { | |
let timeout = null; | |
let callbackArgs = null; | |
const later = () => callback.apply(context, callbackArgs); | |
return (...args) => { | |
callbackArgs = args; | |
clearTimeout(timeout); | |
timeout = setTimeout(later, wait); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment