Skip to content

Instantly share code, notes, and snippets.

@kahl-dev
Created September 8, 2017 17:31
Show Gist options
  • Save kahl-dev/cce12e54e2d58affdaeeff91bb5a857b to your computer and use it in GitHub Desktop.
Save kahl-dev/cce12e54e2d58affdaeeff91bb5a857b to your computer and use it in GitHub Desktop.
ES6 Throttle
function throttle(fn, threshhold = 250, scope, args = []) {
let last, deferTimer;
return function() {
const context = scope || this;
const now = +new Date();
const eventArgs = arguments;
if (last && now < last + threshhold) {
// hold on to it
clearTimeout(deferTimer);
deferTimer = setTimeout(function() {
last = now;
fn.apply(context, [...eventArgs, ...args]);
}, threshhold);
} else {
last = now;
fn.apply(context, [...eventArgs, ...args]);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment