Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Debounce (rate limit) a JS function using function prototype - limits repeated calls to a function (for example when binding to scroll and resize events). See http://www.hnldesign.nl/work/code/debouncing-events-with-jquery/ for more info.
/**
* JavaScript function prototype debouncer 2.0 - hnldesign.nl
* Based on code by Paul Irish and the original debouncing function from John Hann
* http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
* Register debouncer as a function prototype.
* Usage:
* myfunction.deBounce(time, executeasap, caller);
*
* @param threshold - Integer. Time in ms to wait for repeated calls. If time passes without more requests, function is called
* @param execAsap - Boolean. Reverses workings; call function on first request, stop subsequent calls within threshold
* @param caller - String. Original event that requested the repeat, for usage in callback
* @returns function {debounced}
*/
if (typeof Function.prototype.deBounce !== 'function') {
Object.defineProperty(Function.prototype, 'deBounce', {
value : function (threshold, execAsap, caller) {
'use strict';
var func = this;
var timeout;
return function debounced() {
var obj = this;
function delayed() {
if (!execAsap) {
func.apply(obj, [caller]);
}
timeout = null;
}
if (timeout) {
clearTimeout(timeout);
} else {
if (execAsap) {
func.apply(obj, [caller]);
}
}
timeout = setTimeout(delayed, threshold || 100);
};
}
});
}
/**
* Wraps the deBouncer for easy use in jQuery
* Usage:
* jQdeBounce($, 'smartresize', 'resize', 20); //creates the function
* $(window).smartresize(function () { //use the function
* console.log('jquery resize debounce');
* });
*
* @param {object} $ The jQuery object to register in.
* @param {function} createMethod The debounced method/function to create.
* @param {function} originalMethod The original method/function to use as source
*/
if (window.jQuery) {
function jQdeBounce ($, createMethod, originalMethod, thresh, execAsap) {
'use strict';
$.fn[createMethod] = function (fn) { return fn ? this.bind(originalMethod, fn.deBounce(thresh, execAsap)) : this.trigger(createMethod);};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment