Add cancellability to debounce wrapper
This commit is contained in:
parent
c0a9d7465d
commit
364ada6a45
2 changed files with 21 additions and 1 deletions
11
debounce.js
11
debounce.js
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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>
|
||||
|
|
Loading…
Reference in a new issue