Skip to content

Instantly share code, notes, and snippets.

@yy-dev7
Created January 9, 2018 06:21
Show Gist options
  • Save yy-dev7/1e3a8d60b474c44d67de611647256fc8 to your computer and use it in GitHub Desktop.
Save yy-dev7/1e3a8d60b474c44d67de611647256fc8 to your computer and use it in GitHub Desktop.
throttle
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