I've written a quick little helper for event & call debounce/throttling. Since I'm at home and none of my regular code review friends are on-line I figured I'd turn to the great folks here! Would love any feedback you might have.
/**
* debounce
* @param {integer} milliseconds This param indicates the number of milliseconds
* to wait after the last call before calling the original function .
* @return {function} This returns a function that when called will wait the
* indicated number of milliseconds after the last call before
* calling the original function.
*/
Function.prototype.debounce = function (milliseconds) {
var baseFunction = this,
timer = null,
wait = milliseconds;
return function () {
var self = this,
args = arguments;
function complete() {
baseFunction.apply(self, args);
timer = null;
}
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(complete, wait);
};
};
/**
* throttle
* @param {integer} milliseconds This param indicates the number of milliseconds
* to wait between calls before calling the original function.
* @return {function} This returns a function that when called will wait the
* indicated number of milliseconds between calls before
* calling the original function.
*/
Function.prototype.throttle = function (milliseconds) {
var baseFunction = this,
lastEventTimestamp = null,
limit = milliseconds;
return function () {
var self = this,
args = arguments,
now = Date.now();
if (!lastEventTimestamp || now - lastEventTimestamp >= limit) {
lastEventTimestamp = now;
baseFunction.apply(self, args);
}
};
};
To help understand what the point of these helpers are I've prepared this demo: http://jsfiddle.net/zR5jV/1/
GitHub project can be found here: https://github.com/m-gagne/limit.js