fix: debounce.flush invokes func even if never queued before (#3326)

* fix: `debounce.flush` invokes func even if never queued before

* reset after debounced invocation

* account for fn throwing
This commit is contained in:
David Luzar 2021-03-26 17:12:32 +01:00 committed by GitHub
parent b0d7ff290f
commit 5d26c15daf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -123,17 +123,25 @@ export const debounce = <T extends any[]>(
timeout: number,
) => {
let handle = 0;
let lastArgs: T;
let lastArgs: T | null = null;
const ret = (...args: T) => {
lastArgs = args;
clearTimeout(handle);
handle = window.setTimeout(() => fn(...args), timeout);
handle = window.setTimeout(() => {
lastArgs = null;
fn(...args);
}, timeout);
};
ret.flush = () => {
clearTimeout(handle);
fn(...(lastArgs || []));
if (lastArgs) {
const _lastArgs = lastArgs;
lastArgs = null;
fn(..._lastArgs);
}
};
ret.cancel = () => {
lastArgs = null;
clearTimeout(handle);
};
return ret;