Skip to content

Instantly share code, notes, and snippets.

@Rycochet
Created March 6, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rycochet/aa1e2e4195cb631a00d1 to your computer and use it in GitHub Desktop.
Save Rycochet/aa1e2e4195cb631a00d1 to your computer and use it in GitHub Desktop.
Javascript debounce shim
/**
* Make sure that we can't accidentally iterate over custom methods
* @param {Object} proto
* @param {string} fName
* @param {function(?)} fn
*/
function defineProperty(proto, fName, fn) {
if (!proto[fName]) {
proto[fName] = fn;
(Object.defineProperty || $.noop)(proto, fName, {"enumerable": false});
}
}
/**
* Debounce a function, preventing it from being called too often
* @method debounce
* @for Function
* @param {number} [timer] Number of ms to debounce by
* @param {boolean} [wait] Call after delay, otherwise call immediately and don't re-call
*/
defineProperty(FunctionPrototype, "debounce", function(timer, wait) {
var func = this, timeout;
return function() {
var obj = this, args = arguments;
function delayed() {
if (wait) {
func.apply(obj, args);
}
timeout = null;
}
if (timeout) {
clearTimeout(timeout);
} else if (!wait) {
func.apply(obj, args);
}
timeout = setTimeout(delayed, timer || 100);
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment