diff --git a/debounce.js b/debounce.js index 57637ee..a69689e 100644 --- a/debounce.js +++ b/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 } diff --git a/page/debounce.html b/page/debounce.html index fab7a7a..789380b 100644 --- a/page/debounce.html +++ b/page/debounce.html @@ -38,4 +38,15 @@ This code will debounce the update event handler of an input element, calling the update function only after no changes have been made for at least one second. + +

Methods

+

+ The returned wrapper function has two methods: +

+
cancel()
+
Cancels the running timeout without calling the target function.
+
now(...)
+
Cancels the running timeout and calls the target function immediately.
+
+