js/debounce.js

21 lines
453 B
JavaScript
Raw Normal View History

2022-02-08 13:50:32 +00:00
export default (action, delay=1e3) => {
let timeout
2022-02-08 14:15:19 +00:00
const func = (...args) => {
2022-02-08 13:50:32 +00:00
if (timeout) clearTimeout(timeout)
timeout = setTimeout(() => {
timeout = undefined
action(...args)
}, delay)
}
2022-02-08 14:15:19 +00:00
func.cancel = () => {
if (timeout) clearTimeout(timeout)
timeout = undefined
}
func.now = (...args) => {
func.cancel()
return action(...args)
}
Object.defineProperty(func, "running", {get() {return Boolean(timeout)}})
2022-02-08 14:15:19 +00:00
return func
2022-02-08 13:50:32 +00:00
}