https://github.com/martinstark/throttle-ts
Correctly typed, generic, typescript throttle function
https://github.com/martinstark/throttle-ts
throttle typescript
Last synced: about 1 year ago
JSON representation
Correctly typed, generic, typescript throttle function
- Host: GitHub
- URL: https://github.com/martinstark/throttle-ts
- Owner: martinstark
- License: mit
- Created: 2020-12-01T16:19:11.000Z (over 5 years ago)
- Default Branch: main
- Last Pushed: 2025-03-24T23:29:28.000Z (about 1 year ago)
- Last Synced: 2025-03-27T09:21:55.203Z (about 1 year ago)
- Topics: throttle, typescript
- Language: TypeScript
- Homepage:
- Size: 852 KB
- Stars: 9
- Watchers: 0
- Forks: 0
- Open Issues: 11
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE.md
Awesome Lists containing this project
README
# throttle-ts
Correctly typed, generic, tiny ([419B](https://bundlephobia.com/package/throttle-ts@1.4.0)), typescript throttle function.
```typescript
const fn = (str: string, num: number) => `hello ${str} ${num}`;
const [throttled, cancel, reset] = throttle(fn, 500);
throttled("world", 1);
```
Yields the return value of the throttled function, or undefined when throttled/cancelled.
The throttled function keeps the type signature of the original function, plus `undefined`.

Returns a `cancel` function which enables cleanup of the timeout, and blocks future calls to the throttled function. Useful when unmounting (react) ui components.
Returns a `reset` function which enables clearing the timeout, letting you call the method again before the delay has expired.
### Usage
```bash
npm i throttle-ts
```
```javascript
import { throttle } from "throttle-ts";
```
```javascript
const fn = () => "executed";
const [throttledFn] = throttle(fn, 200);
throttledFn(); // "executed"
throttledFn(); // undefined
throttledFn(); // undefined
setTimeout(throttledFn, 500); // "executed"
```
### Using Cancel
```javascript
const fn = () => "executed";
const [throttledFn, cancel] = throttle(fn, 200);
throttledFn(); // "executed"
setTimeout(throttledFn, 500); // undefined
cancel(); // blocks all future calls to the throttled function
```
### Using Reset
```javascript
const fn = () => "executed";
const [throttledFn, _, reset] = throttle(fn, 200);
throttledFn(); // "executed"
throttledFn(); // undefined
reset(); // reset delay timeout
throttledFn(); // "executed"
throttledFn(); // undefined
```