Skip to content

Instantly share code, notes, and snippets.

@mckamey
Created July 16, 2012 22:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mckamey/3125441 to your computer and use it in GitHub Desktop.
Save mckamey/3125441 to your computer and use it in GitHub Desktop.
Debounce closure
/**
* Creates a function which fires only once when called in quick succession
* @param {function...} action the function to fire
* @param {number} delay amount of time until considered done, default:100ms
* @param {boolean} asap if should execute at the start of the series (true) or the end (false), default:false
* return {function} debounced function
*/
var debounce = function(action, delay, asap){
if ('function' !== typeof action) {
return null;
}
// default to 100ms
delay = (+delay || 100);//ms
var timer = 0,
fire = function(){
if (timer) {
clearTimeout(timer);
timer = 0;
}
if (!asap) {
action();
}
};
return function() {
if (timer) {
clearTimeout(timer);
} else if (asap) {
action();
}
timer = setTimeout(fire, delay);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment