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:
parent
b0d7ff290f
commit
5d26c15daf
14
src/utils.ts
14
src/utils.ts
@ -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;
|
||||
|
Loading…
x
Reference in New Issue
Block a user