Skip to content

Instantly share code, notes, and snippets.

@Sceat
Last active July 6, 2022 19:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sceat/e6bdafe5f19d55b76e788816f3dc78ae to your computer and use it in GitHub Desktop.
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"
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)
}
}
{
"name": "debounce",
"version": "0.1.0",
"type": "module",
"main": "debounce.js"
}
@Sceat
Copy link
Author

Sceat commented Jun 10, 2020

Will execute after 100ms when calls stops

import debounce from 'debounce'
const debounce_100 = debounce(100)
const debounce_me = debounce_100(() => { console.log('debounced') })

debounce_me()
debounce_me()

Will execute at least once after 1s

import debounce from 'debounce'
const debounce_100_max_1000 = debounce(100, 1000)
const debounce_me = debounce_100_max_1000(() => { console.log('debounced') })

debounce_me()
debounce_me()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment