Skip to content

Instantly share code, notes, and snippets.

@Natfan
Last active December 10, 2022 04:00
Show Gist options
  • Save Natfan/25d72b2cf726bbf3443d8f73f4df813e to your computer and use it in GitHub Desktop.
Save Natfan/25d72b2cf726bbf3443d8f73f4df813e to your computer and use it in GitHub Desktop.
//debouncer.js
/*
This is the typical debouncer function that receives
the "callback" and the time it will wait to emit the event
*/
function debouncer (fn, delay) {
var timeoutID = null
return (() => {
clearTimeout(timeoutID)
timeoutID = setTimeout(() => fn.apply(this, arguments), delay)
})
}
/*
this function receives the element where the directive
will be set in and also the value set in it
if the value has changed then it will rebind the event
it has a default timeout of 500 milliseconds
*/
function debounce(el, binding) {
if (binding.value === binding.oldValue) return
el.oninput = debouncer(function() {
el.dispatchEvent(new Event('change'))
}, parseInt(binding.value) || 500)
}
export { debounce }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment