Skip to content

Instantly share code, notes, and snippets.

@joladev
Created April 2, 2014 08:05
Show Gist options
  • Save joladev/9929890 to your computer and use it in GitHub Desktop.
Save joladev/9929890 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