Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion packages/core/src/utils/throttle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,23 +27,28 @@ export function throttle<T extends (...args: unknown[]) => void>(
const leading = options?.leading ?? true;
let timer: ReturnType<typeof setTimeout> | undefined;
let lastArgs: Parameters<T> | undefined;
let hasNewCalls = false;

const throttled = function (...args: Parameters<T>) {
lastArgs = args;
if (!timer) {
if (leading) func(...args);
timer = setTimeout(() => {
timer = undefined;
if (lastArgs !== args || !leading) func(...lastArgs!);
if (hasNewCalls || !leading) func(...lastArgs!);
lastArgs = undefined;
hasNewCalls = false;
}, wait);
} else {
hasNewCalls = true;
}
} as T & { cancel: () => void };

throttled.cancel = () => {
clearTimeout(timer);
timer = undefined;
lastArgs = undefined;
hasNewCalls = false;
};

return throttled;
Expand Down
Loading