Skip to content

Instantly share code, notes, and snippets.

@rgrove
Created October 5, 2011 21:33
Show Gist options
  • Save rgrove/1265810 to your computer and use it in GitHub Desktop.
Save rgrove/1265810 to your computer and use it in GitHub Desktop.
Better Y.throttle()
// New Y.throttle().
Y.throttle = function (fn, duration, context) {
var lastTime = 0,
lastArgs, timeout;
duration || (duration = Y.config.throttleTime || 150);
function execute() {
var args = lastArgs;
lastArgs = null;
lastTime = Y.Lang.now();
timeout = null;
fn.apply(context, args);
}
return function () {
var now;
lastArgs = arguments;
if (timeout) { return; }
now = Y.Lang.now();
if (now - lastTime > duration) {
lastArgs = null;
lastTime = now;
fn.apply(context, arguments);
} else {
timeout = setTimeout(execute, duration);
}
};
};
// Old Y.throttle().
Y.throttle = function(fn, ms) {
ms = (ms) ? ms : (Y.config.throttleTime || 150);
if (ms === -1) {
return (function() {
fn.apply(null, arguments);
});
}
var last = Y.Lang.now();
return (function() {
var now = Y.Lang.now();
if (now - last > ms) {
last = now;
fn.apply(null, arguments);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment