Skip to content

Instantly share code, notes, and snippets.

@telic
Created April 24, 2017 01:30
Show Gist options
  • Save telic/9329d3f65af355bfbd578ef2564a4c4d to your computer and use it in GitHub Desktop.
Save telic/9329d3f65af355bfbd578ef2564a4c4d to your computer and use it in GitHub Desktop.
Simple es6 throttle with leading and trailing-edge calls
function throttle(fn, threshold=250) {
let hold = false;
let trail;
let timeout = function() {
if (trail !== undefined) {
fn.apply(trail[0], trail[1]);
trail = undefined;
setTimeout(timeout, threshold)
} else {
hold = false;
}
};
return function(...args) {
if (!hold) {
fn.apply(this, args);
hold = true;
setTimeout(timeout, threshold);
} else {
trail = [this, args];
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment