Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add leading option for debounce #128

Merged
merged 6 commits into from
Aug 15, 2024
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
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)
})
})
Loading