Last active
July 6, 2022 19:15
-
-
Save Sceat/e6bdafe5f19d55b76e788816f3dc78ae to your computer and use it in GitHub Desktop.
Debounce a function call with a fail safe to avoid "kicking down the road"
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
export default (min_delay, max_delay = Infinity) => handler => { | |
let min_timeout | |
let max_timeout | |
let security_started | |
const execute = () => { | |
clearTimeout(max_timeout) | |
handler() | |
security_started = false | |
} | |
return () => { | |
if (!security_started && max_delay !== Infinity) { | |
security_started = true | |
clearTimeout(max_timeout) | |
max_timeout = setTimeout(() => execute(), max_delay) | |
} | |
clearTimeout(min_timeout) | |
min_timeout = setTimeout(execute, min_delay) | |
} | |
} |
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
{ | |
"name": "debounce", | |
"version": "0.1.0", | |
"type": "module", | |
"main": "debounce.js" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Will execute after 100ms when calls stops
Will execute at least once after 1s