Created
October 5, 2011 21:33
-
-
Save rgrove/1265810 to your computer and use it in GitHub Desktop.
Better Y.throttle()
This file contains hidden or 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
// 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