Created
April 24, 2017 01:30
-
-
Save telic/9329d3f65af355bfbd578ef2564a4c4d to your computer and use it in GitHub Desktop.
Simple es6 throttle with leading and trailing-edge calls
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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