Skip to content

Instantly share code, notes, and snippets.

@timwright12
Created June 15, 2018 20:03
Show Gist options
  • Save timwright12/e3b9f3df8803b2fab8346ea7b47bdfdb to your computer and use it in GitHub Desktop.
Save timwright12/e3b9f3df8803b2fab8346ea7b47bdfdb to your computer and use it in GitHub Desktop.
/** @function
* @name debounce
* @description Utility method for debouncing the resize event
* @param {function} func
* @param {number} wait
* @param {object} immediate
* @example var myEfficientFn = debounce(function() { things to do }, 250);
* @example window.addEventListener( 'resize', myEfficientFn );
*/
var debounce = function ( func, wait, immediate ) {
var timeout;
return function() {
var context = this;
var args = arguments;
var later = function() {
timeout = null;
if ( ! immediate ) {
func.apply( context, args );
}
};
var callNow = immediate && !timeout;
window.clearTimeout( timeout );
timeout = window.setTimeout( later, wait );
if ( callNow ) {
func.apply( context, args );
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment