Skip to content

Instantly share code, notes, and snippets.

@kemayo
Created December 12, 2011 21:43
Show Gist options
  • Save kemayo/1469241 to your computer and use it in GitHub Desktop.
Save kemayo/1469241 to your computer and use it in GitHub Desktop.
// Creates a throttled function, which will run *at most* every `delay`.
// It'll run immediately the first time you call it, because that's a very
// long time since it was last called, as it were.
// e.g. set up a scroll handler which will be called once every 500ms at most
// $(window).bind('scroll', throttle(my_expensive_scroll_handler, 500));
var throttle = function(callback, delay) {
var timeout
,last_run = 0;
return function () {
if (timeout) {
return;
}
var elapsed = (+new Date()) - last_run
,context = this
,args = arguments
,run_callback = function() {
last_run = +new Date();
timeout = false;
callback.apply(context, args);
}
;
if (elapsed >= delay) {
run_callback();
}
else {
timeout = setTimeout(run_callback, delay);
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment