Skip to content

Instantly share code, notes, and snippets.

@kristw
Last active August 29, 2015 14:11
Show Gist options
  • Save kristw/86813a4caec2d5b6deea to your computer and use it in GitHub Desktop.
Save kristw/86813a4caec2d5b6deea to your computer and use it in GitHub Desktop.
Smart Debounce
// An improved version of the classic "debounce" function.
// var doSomething = debounce(fn);
// doSomething(params); will debounce.
// doSomething.now(params) will execute immediately.
//---------------------------------------------------
// Modified from lodash's debounce
//---------------------------------------------------
/**
* Returns a function, that, as long as it continues to be invoked,
* will not be triggered.
* The function will be called after it stops being called for
* "wait" milliseconds.
* The output function can be called with .now() to execute immediately
* For example:
* doSomething(params); // will debounce
* doSomething.now(params); // will execute immediately
*
* @param Function func function to be debounced
* @param Number wait wait time until it will be executed
* @param Boolean immediate If "immediate" is passed, trigger the function on the
* leading edge, instead of the trailing.
* @return Function debounced function
*/
function debounce(func, wait, immediate) {
var timeout;
var outputFn = function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
// return caller for chaining
return context;
};
// so we know this function is debounced
outputFn.isDebounced = true;
// and provide a way to call the original function immediately
outputFn.now = function(){
clearTimeout(timeout);
return func.apply(this, arguments);
};
return outputFn;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment