Last active
September 12, 2022 12:01
-
-
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!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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