Created
January 9, 2018 06:21
-
-
Save yy-dev7/1e3a8d60b474c44d67de611647256fc8 to your computer and use it in GitHub Desktop.
throttle
This file contains 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, delay = 200) { | |
let now | |
let lastExec | |
let timer | |
let context | |
let args | |
const execute = () => { | |
fn.apply(context, args) | |
lastExec = now | |
} | |
return (...callArgs) => { | |
context = this | |
args = callArgs | |
now = Date.now() | |
if (timer) { | |
clearTimeout(timer) | |
timer = null | |
} | |
if (lastExec) { | |
const diff = delay - (now - lastExec) | |
if (diff < 0) { | |
execute() | |
} else { | |
timer = setTimeout(() => { | |
execute() | |
}, diff) | |
} | |
} else { | |
execute() | |
} | |
} | |
} | |
export default throttle |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment