Add cancellability to debounce wrapper

This commit is contained in:
Talia 2022-02-08 15:15:19 +01:00
parent c0a9d7465d
commit 364ada6a45
2 changed files with 21 additions and 1 deletions

View file

@ -1,10 +1,19 @@
export default (action, delay=1e3) => {
let timeout
return (...args) => {
const func = (...args) => {
if (timeout) clearTimeout(timeout)
timeout = setTimeout(() => {
timeout = undefined
action(...args)
}, delay)
}
func.cancel = () => {
if (timeout) clearTimeout(timeout)
timeout = undefined
}
func.now = (...args) => {
func.cancel()
return action(...args)
}
return func
}

View file

@ -38,4 +38,15 @@
This code will debounce the update event handler of an input element, calling the <code>update</code>
function only after no changes have been made for at least one second.
<h2>Methods</h2>
<p>
The returned wrapper function has two methods:
<dl>
<dt><code>cancel()</code></dt>
<dd>Cancels the running timeout without calling the target function.</dd>
<dt><code>now(...)</code></dt>
<dd>Cancels the running timeout and calls the target function immediately.</dd>
</dl>
</p>
</section>