Skip to content

Instantly share code, notes, and snippets.

@argyleink
Last active September 12, 2022 12:01
Show Gist options
  • Save argyleink/5493307 to your computer and use it in GitHub Desktop.
Save argyleink/5493307 to your computer and use it in GitHub Desktop.
Debounce your events, so they can't lock your UI while spammed. Control the flow!
// As taken from the UnderscoreJS utility framework
function debounce(func, wait, immediate) {
let timeout
return function() {
let context = this
, args = arguments
let later = function() {
timeout = null
if (!immediate) func.apply(context, args)
}
let callNow = immediate && !timeout
clearTimeout(timeout)
timeout = setTimeout(later, wait)
if (callNow) func.apply(context, args)
}
}
// EXAMPLE: Add the resize callback but only allow it to execute once every 300 milliseconds
window.addEventListener('resize', debounce((event) => {
// Do the resize processing (whatever you'd like to do!)
}, 300))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment