Created
July 16, 2012 22:14
-
-
Save mckamey/3125441 to your computer and use it in GitHub Desktop.
Debounce closure
This file contains 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
/** | |
* 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