Skip to content

Commit

Permalink
feat(debounce): add leading option (#128)
Browse files Browse the repository at this point in the history
  • Loading branch information
crishoj authored Aug 15, 2024
1 parent dd34b7d commit 942057e
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
9 changes: 9 additions & 0 deletions docs/curry/debounce.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,15 @@ debounce Invocations: x x x x - - - - - - - - x x x x x x x x x x - - - - - - -
Source Invocations: - - - - - - - - - - x - - - - - - - - - - - - - - - - - x - - - - -
```

The `leading` option decides whether the source function is called on the first
invocation of the throttle function or not.

```sh
Time: 0ms - - - - 100ms - - - - 200ms - - - - 300ms - - - - 400ms - - - -
debounce Invocations: x x x x - - - - - - - - x x x x x x x x x x - - - - - - - - - - - -
Source Invocations: x - - - - - - - - - x - - - - - - - - - - - - - - - - - x - - - - -
```

### Cancel

The function returned by `debounce` has a `cancel` method that when called will permanently stop the source function from being debounced.
Expand Down
18 changes: 17 additions & 1 deletion src/curry/debounce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,19 @@ export type DebounceFunction<TArgs extends any[]> = {
* ```
*/
export function debounce<TArgs extends any[]>(
{ delay }: { delay: number },
{
delay,
leading = false,
}: {
delay: number
/**
* Decides whether the source function is called on the first
* invocation of the throttle function or not
*
* @default false
*/
leading?: boolean
},
func: (...args: TArgs) => any,
): DebounceFunction<TArgs> {
let timer: unknown = undefined
Expand All @@ -50,6 +62,10 @@ export function debounce<TArgs extends any[]>(
active && func(...args)
timer = undefined
}, delay)
if (leading) {
func(...args)
leading = false
}
} else {
func(...args)
}
Expand Down
8 changes: 8 additions & 0 deletions tests/curry/debounce.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,4 +75,12 @@ describe('debounce', () => {
vi.advanceTimersByTime(delay + 10)
expect(mockFunc).toHaveBeenCalledTimes(0)
})

test('executes the function immediately on the first invocation when `leading` is `true`', async () => {
func = _.debounce({ delay: delay, leading: true }, mockFunc)
runFunc3Times()
expect(mockFunc).toHaveBeenCalledTimes(1)
vi.advanceTimersByTime(delay + 10)
expect(mockFunc).toHaveBeenCalledTimes(2)
})
})

0 comments on commit 942057e

Please sign in to comment.