Skip to content

Instantly share code, notes, and snippets.

@jupegarnica
Forked from bitfishxyz/throttle.js
Created February 12, 2020 14:27
Show Gist options
  • Select an option

  • Save jupegarnica/0f5c54520034b5f8d5f33908ecd70558 to your computer and use it in GitHub Desktop.

Select an option

Save jupegarnica/0f5c54520034b5f8d5f33908ecd70558 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