Skip to content

Instantly share code, notes, and snippets.

@jupegarnica
Forked from bitfishxyz/debounce.js
Created February 12, 2020 14:27
Show Gist options
  • Save jupegarnica/4ac4be2fd14f87edeb1c6b309c55123e to your computer and use it in GitHub Desktop.
Save jupegarnica/4ac4be2fd14f87edeb1c6b309c55123e to your computer and use it in GitHub Desktop.
const debounce = (func, time = 17, options = {
leading: true,
context: null
}) => {
let timer;
const _debounce = function (...args) {
if (timer) {
clearTimeout(timer)
}
if (options.leading && !timer) {
timer = setTimeout(null, time)
func.apply(options.context, args)
}else{
timer = setTimeout(() => {
func.apply(options.context, args)
timer = null
}, time)
}
};
_debounce.cancel = function () {
clearTimeout(timer)
timer = null
};
return _debounce
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment