Skip to content
Merged
Show file tree
Hide file tree
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
6 changes: 5 additions & 1 deletion src/core/utils/function.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,11 @@ export function debounce<TArgs extends unknown[]>(
const now = Date.now();
if (leading && !leadingDone) {
leadingDone = true;
invoke(args, trailing, now);
// Clear pendingArgs on the leading invoke so a SINGLE call does not also
// fire the trailing edge. A subsequent call within the window re-sets
// pendingArgs (the leading branch is skipped), so the trailing edge still
// fires when the function was called more than once (lodash semantics).
invoke(args, false, now);
}
clearTrailing();
timeoutId = setTimeout(trailingTrigger, delayMs);
Expand Down
6 changes: 4 additions & 2 deletions tests/utils-function-extras.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,15 +121,17 @@ describe('utils/function extras', () => {
expect(calls).toEqual([1, 3]);
});

it('debounce(leading: true, trailing: true) keeps a single call for the trailing edge', async () => {
it('debounce(leading: true, trailing: true) does not double-invoke a single call (#178)', async () => {
const calls: number[] = [];
const fn = debounce((n: number) => calls.push(n), 30, { leading: true, trailing: true });

fn(1);

// Leading fires immediately; the trailing edge must NOT fire for a single
// call (lodash semantics: trailing only when called more than once).
expect(calls).toEqual([1]);
await wait(60);
expect(calls).toEqual([1, 1]);
expect(calls).toEqual([1]);
});

it('debounce maxWait forces invocation', async () => {
Expand Down