Created
March 6, 2015 13:57
-
-
Save Rycochet/aa1e2e4195cb631a00d1 to your computer and use it in GitHub Desktop.
Javascript debounce shim
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
/** | |
* 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