Created
January 19, 2020 03:06
-
-
Save bitfishxyz/a1203054ebabaf721f10de4b1165f36f to your computer and use it in GitHub Desktop.
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
const throttle = (func, time = 17, options = { | |
leading: true, | |
trailing: false, | |
context: null | |
}) => { | |
let previous = new Date(0).getTime() | |
let timer; | |
const _throttle = function (...args) { | |
let now = new Date().getTime(); | |
if (!options.leading) { | |
if (timer) return | |
timer = setTimeout(() => { | |
timer = null | |
func.apply(options.context, args) | |
}, time) | |
} else if (now - previous > time) { | |
func.apply(options.context, args) | |
previous = now | |
} else if (options.trailing) { | |
clearTimeout(timer) | |
timer = setTimeout(() => { | |
func.apply(options.context, args) | |
}, time) | |
} | |
}; | |
_throttle.cancel = () => { | |
previous = 0; | |
clearTimeout(timer); | |
timer = null | |
}; | |
return _throttle | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment