Skip to content

Commit

Permalink
docs: ✏️ throttle documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
lrodrigues-newstore committed Feb 8, 2025
1 parent ca4fbc4 commit 2c9df7b
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 27 deletions.
25 changes: 0 additions & 25 deletions packages/throttle/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,31 +12,6 @@ A tiny throttler.
yarn add @pacote/throttle
```

## Usage

```typescript
import { throttle } from '@pacote/throttle'

const throttledFn = throttle(fn, 100)

throttledFn() // fn() is called immediately
throttledFn() // fn() is scheduled for execution after 100ms
throttledFn() // fn() is scheduled for execution, cancelling the previous one
```

### `throttle<T>(fn: (...args: T[]) => any, delay = 0): (...args: T[]) => void`

`throttle()` creates a throttled version of the passed function.

By calling the throttled function repeatedly, the original function is called
once immediately and then at most once for every period of time determined by
the `delay` argument.

The `delay` argument is optional and defaults to `0` when not supplied.

The throttled function supplies a `.cancel()` method that can be used to cancel
a pending invocation.

## License

MIT © [Luís Rodrigues](https://goblindegook.com).
27 changes: 25 additions & 2 deletions packages/throttle/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,34 @@ interface Cancellable {
cancel: () => void
}

/**
* Creates a throttled version of the passed function.
*
* By calling the throttled function repeatedly, the original function is called
* once immediately and then at most once for every period of time determined by
* the `delay` argument.
*
* @param fn The function to throttle. Can accept any number of arguments.
* @param delay The minimum time (in milliseconds) that must pass between successive calls.
* Defaults to 0.
*
* @returns A throttled version of the input function with an additional `cancel()` method.
* The cancel method can be used to reset the throttle timer.
*
* @example
* import { throttle } from '@pacote/throttle'
*
* const throttledFn = throttle(fn, 100)
*
* throttledFn() // fn() is called immediately
* throttledFn() // fn() is scheduled for execution after 100ms
* throttledFn() // fn() is scheduled for execution, cancelling the previous one
*/
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
export function throttle<A extends any[]>(
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
fn: (...args: A) => any,
delay = 0,
delay = 0
): Throttled<A> & Cancellable {
let lastCalled = 0
let timer: NodeJS.Timeout
Expand All @@ -33,6 +56,6 @@ export function throttle<A extends any[]>(
cancel: () => {
lastCalled = 0
clearTimeout(timer)
},
}
})
}

0 comments on commit 2c9df7b

Please sign in to comment.