Skip to content

Instantly share code, notes, and snippets.

@oddvalue
Last active September 17, 2018 14:55
Show Gist options
  • Save oddvalue/7e7fd538762aa1d30325c12c4410fca4 to your computer and use it in GitHub Desktop.
Save oddvalue/7e7fd538762aa1d30325c12c4410fca4 to your computer and use it in GitHub Desktop.
Debounce
/**
* 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