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,
|
timeout: number,
|
||||||
) => {
|
) => {
|
||||||
let handle = 0;
|
let handle = 0;
|
||||||
let lastArgs: T;
|
let lastArgs: T | null = null;
|
||||||
const ret = (...args: T) => {
|
const ret = (...args: T) => {
|
||||||
lastArgs = args;
|
lastArgs = args;
|
||||||
clearTimeout(handle);
|
clearTimeout(handle);
|
||||||
handle = window.setTimeout(() => fn(...args), timeout);
|
handle = window.setTimeout(() => {
|
||||||
|
lastArgs = null;
|
||||||
|
fn(...args);
|
||||||
|
}, timeout);
|
||||||
};
|
};
|
||||||
ret.flush = () => {
|
ret.flush = () => {
|
||||||
clearTimeout(handle);
|
clearTimeout(handle);
|
||||||
fn(...(lastArgs || []));
|
if (lastArgs) {
|
||||||
|
const _lastArgs = lastArgs;
|
||||||
|
lastArgs = null;
|
||||||
|
fn(..._lastArgs);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
ret.cancel = () => {
|
ret.cancel = () => {
|
||||||
|
lastArgs = null;
|
||||||
clearTimeout(handle);
|
clearTimeout(handle);
|
||||||
};
|
};
|
||||||
return ret;
|
return ret;
|
||||||
|
Loading…
x
Reference in New Issue
Block a user