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)
|
|
|
|
}
|
2022-02-08 14:27:55 +00:00
|
|
|
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
|
|
|
}
|