From 364ada6a45835e0cfc122d1f46b79e06e1ed0894 Mon Sep 17 00:00:00 2001 From: DarkWiiPlayer Date: Tue, 8 Feb 2022 15:15:19 +0100 Subject: [PATCH] Add cancellability to debounce wrapper --- debounce.js | 11 ++++++++++- page/debounce.html | 11 +++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) 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.
+
+