Skip to content

Instantly share code, notes, and snippets.

@joshuafcole
Created November 27, 2013 19:28
Show Gist options
  • Save joshuafcole/7681676 to your computer and use it in GitHub Desktop.
Save joshuafcole/7681676 to your computer and use it in GitHub Desktop.
throttle = function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
options || (options = {});
var later = function() {
previous = options.leading === false ? 0 : getTime();
timeout = null;
result = func.apply(context, args);
context = args = null;
};
return function() {
var now = getTime();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
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