Skip to content

Instantly share code, notes, and snippets.

@plugn
Forked from joladev/throttle.js
Created April 18, 2016 13:29
Show Gist options
  • Select an option

  • Save plugn/73c587fa1a103f957f5b4be052163712 to your computer and use it in GitHub Desktop.

Select an option

Save plugn/73c587fa1a103f957f5b4be052163712 to your computer and use it in GitHub Desktop.
// Throttle from underscore.js, simplified and deattached
var throttle = function(func, wait) {
var context, args, result;
var timeout = null;
var previous = 0;
var later = function() {
previous = Date.now();
timeout = null;
result = func.apply(context, args);
context = args = null;
};
return function() {
var now = Date.now();
if (!previous) 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) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment