Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/little-planets-serve.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/pacer': patch
---

Fixed a bug in AsyncDebouncer where a scheduled execution is dropped if an in-flight execution completes before it is invoked
3 changes: 1 addition & 2 deletions packages/pacer/src/async-debouncer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,7 @@ export class AsyncDebouncer<TFn extends AnyAsyncFunction> {
const currentMaybeExecuteCount = this.store.state.maybeExecuteCount + 1

try {
this.#setState({ isExecuting: true })
this.#setState({ isExecuting: true, lastArgs: undefined })
Comment thread
coderabbitai[bot] marked this conversation as resolved.
const currentAsyncRetryer = new AsyncRetryer(
this.fn,
this.options.asyncRetryerOptions,
Expand All @@ -391,7 +391,6 @@ export class AsyncDebouncer<TFn extends AnyAsyncFunction> {
this.#setState({
isExecuting: false,
isPending: false,
lastArgs: undefined,
settleCount: this.store.state.settleCount + 1,
})
this.options.onSettled?.(args, this)
Expand Down
33 changes: 33 additions & 0 deletions packages/pacer/tests/async-debouncer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,39 @@ describe('AsyncDebouncer', () => {
expect(mockFn).toHaveBeenLastCalledWith('fifth')
await promise5
})

it('should execute a trailing call scheduled after a prior execution', async () => {
const mockFn = vi.fn(
(_: string) =>
new Promise((resolve) => setTimeout(() => resolve('result'), 500)),
)
const debouncer = new AsyncDebouncer(mockFn, {
wait: 1000,
leading: true,
trailing: true,
})

// First call - should execute immediately
const promise1 = debouncer.maybeExecute('first')
expect(mockFn).toBeCalledTimes(1)
expect(mockFn).toBeCalledWith('first')

// Second call enqueued during first execution
const promise2 = debouncer.maybeExecute('second')
expect(mockFn).toBeCalledTimes(1)

// Advance past first execution
vi.advanceTimersByTime(500)
await promise1

// Trigger second execution
vi.advanceTimersByTime(1000)
await promise2

// Verify trailing execution occurred
expect(mockFn).toBeCalledTimes(2)
expect(mockFn).toHaveBeenLastCalledWith('second')
})
})

describe('Promise Handling', () => {
Expand Down