Skip to content

Instantly share code, notes, and snippets.

@edwinwebb
Created April 30, 2015 09:40
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 edwinwebb/e71bde8b00ff40f3f046 to your computer and use it in GitHub Desktop.
Save edwinwebb/e71bde8b00ff40f3f046 to your computer and use it in GitHub Desktop.
Javascript Throttle Function
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. Normally, the throttled function will run
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `{leading: false}`. To disable execution on the trailing edge, ditto.
// Replaced namespace and _.now function to function scope
// https://github.com/jashkenas/underscore/blob/master/underscore.js#L779
function throttle(func, wait, options) {
var _ = {
now : Date.now || function() {
return new Date().getTime();
}
}
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function() {
previous = options.leading === false ? 0 : _.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function() {
var now = _.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment