Skip to content

Instantly share code, notes, and snippets.

@bitfishxyz
Created January 19, 2020 03:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bitfishxyz/a1203054ebabaf721f10de4b1165f36f to your computer and use it in GitHub Desktop.
Save bitfishxyz/a1203054ebabaf721f10de4b1165f36f to your computer and use it in GitHub Desktop.
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