Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@russellbeattie
Last active August 18, 2016 01:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save russellbeattie/b6b71b1e5b48122866fb6f77fdbd5567 to your computer and use it in GitHub Desktop.
Save russellbeattie/b6b71b1e5b48122866fb6f77fdbd5567 to your computer and use it in GitHub Desktop.
A better, self-contained, JavaScript function throttle
function throttle(fn, limit, scope) {
var last;
var deferTimer;
return function() {
var context = scope || this;
var args = arguments;
var now = Date.now();
var diff = now - last;
clearTimeout(deferTimer);
if (diff < limit) {
deferTimer = setTimeout(function() {
last = Date.now();
fn.apply(context, args);
}, limit - diff);
} else {
last = now;
fn.apply(context, args);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment