Skip to content

Commit

Permalink
Add signal option and remove abort() method (#53)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <[email protected]>
  • Loading branch information
liuhanqu and sindresorhus authored Nov 30, 2024
1 parent 31db2ba commit b0eadea
Show file tree
Hide file tree
Showing 5 changed files with 103 additions and 43 deletions.
49 changes: 34 additions & 15 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,3 @@
export class AbortError extends Error {
readonly name: 'AbortError';

private constructor();
}

type AnyFunction = (...arguments_: readonly any[]) => unknown;

export type ThrottledFunction<F extends AnyFunction> = F & {
Expand All @@ -18,11 +12,6 @@ export type ThrottledFunction<F extends AnyFunction> = F & {
The number of queued items waiting to be executed.
*/
readonly queueSize: number;

/**
Abort pending executions. All unresolved promises are rejected with a `pThrottle.AbortError` error.
*/
abort(): void;
};

export type Options = {
Expand All @@ -44,7 +33,37 @@ export type Options = {
readonly strict?: boolean;

/**
Get notified when function calls are delayed due to exceeding the `limit` of allowed calls within the given `interval`. The delayed call arguments are passed to the `onDelay` callback.
Abort pending executions. When aborted, all unresolved promises are rejected with `signal.reason`.
@example
```
import pThrottle from 'p-throttle';
const controller = new AbortController();
const throttle = pThrottle({
limit: 2,
interval: 1000,
signal: controller.signal
});
const throttled = throttle(() => {
console.log('Executing...');
});
await throttled();
await throttled();
controller.abort('aborted')
await throttled();
//=> Executing...
//=> Executing...
//=> Promise rejected with reason `aborted`
```
*/
signal?: AbortSignal;

/**
Get notified when function calls are delayed due to exceeding the `limit` of allowed calls within the given `interval`.
Can be useful for monitoring the throttling efficiency.
Expand All @@ -60,9 +79,9 @@ export type Options = {
},
});
const throttled = throttle((a, b) => {
console.log(`Executing with ${a} ${b}...`);
});
const throttled = throttle(() => {
console.log('Executing...');
});
await throttled(1, 2);
await throttled(3, 4);
Expand Down
20 changes: 11 additions & 9 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
export class AbortError extends Error {
constructor() {
super('Throttled function aborted');
this.name = 'AbortError';
}
}
const registry = new FinalizationRegistry(({signal, aborted}) => {
signal?.removeEventListener('abort', aborted);
});

export default function pThrottle({limit, interval, strict, onDelay}) {
export default function pThrottle({limit, interval, strict, signal, onDelay}) {
if (!Number.isFinite(limit)) {
throw new TypeError('Expected `limit` to be a finite number');
}
Expand Down Expand Up @@ -91,16 +88,21 @@ export default function pThrottle({limit, interval, strict, onDelay}) {
});
};

throttled.abort = () => {
const aborted = () => {
for (const timeout of queue.keys()) {
clearTimeout(timeout);
queue.get(timeout)(new AbortError());
queue.get(timeout)(signal.reason);
}

queue.clear();
strictTicks.splice(0, strictTicks.length);
};

registry.register(throttled, {signal, aborted});

signal?.throwIfAborted();
signal?.addEventListener('abort', aborted, {once: true});

throttled.isEnabled = true;

Object.defineProperty(throttled, 'queueSize', {
Expand Down
12 changes: 9 additions & 3 deletions index.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,34 @@
import {expectType} from 'tsd';
import pThrottle, {type ThrottledFunction} from './index.js';

const unicornController = new AbortController();
const throttledUnicorn = pThrottle({
limit: 1,
interval: 1000,
signal: unicornController.signal,
})((_index: string) => '🦄');

const lazyUnicornController = new AbortController();
const throttledLazyUnicorn = pThrottle({
limit: 1,
interval: 1000,
signal: lazyUnicornController.signal,
})(async (_index: string) => '🦄');

const taggedUnicornController = new AbortController();
const throttledTaggedUnicorn = pThrottle({
limit: 1,
interval: 1000,
signal: taggedUnicornController.signal,
})((_index: number, tag: string) => `${tag}: 🦄`);

expectType<string>(throttledUnicorn(''));
expectType<string>(await throttledLazyUnicorn(''));
expectType<string>(throttledTaggedUnicorn(1, 'foo'));

throttledUnicorn.abort();
throttledLazyUnicorn.abort();
throttledTaggedUnicorn.abort();
unicornController.abort();
lazyUnicornController.abort();
taggedUnicornController.abort();

expectType<boolean>(throttledUnicorn.isEnabled);
expectType<number>(throttledUnicorn.queueSize);
Expand Down
34 changes: 30 additions & 4 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,36 @@ Default: `false`

Use a strict, more resource intensive, throttling algorithm. The default algorithm uses a windowed approach that will work correctly in most cases, limiting the total number of calls at the specified limit per interval window. The strict algorithm throttles each call individually, ensuring the limit is not exceeded for any interval.

#### signal

Type: [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)

Abort pending executions. When aborted, all unresolved promises are rejected with `signal.reason`.

```js
import pThrottle from 'p-throttle';

const controller = new AbortController();

const throttle = pThrottle({
limit: 2,
interval: 1000,
signal: controller.signal
});

const throttled = throttle(() => {
console.log('Executing...');
});

await throttled();
await throttled();
controller.abort('aborted')
await throttled();
//=> Executing...
//=> Executing...
//=> Promise rejected with reason `aborted`
```

##### onDelay

Type: `Function`
Expand Down Expand Up @@ -119,10 +149,6 @@ Type: `Function`

A promise-returning/async function or a normal function.

### throttledFn.abort()

Abort pending executions. All unresolved promises are rejected with a `pThrottle.AbortError` error.

### throttledFn.isEnabled

Type: `boolean`\
Expand Down
31 changes: 19 additions & 12 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import test from 'ava';
import inRange from 'in-range';
import timeSpan from 'time-span';
import delay from 'delay';
import pThrottle, {AbortError} from './index.js';
import pThrottle from './index.js';

const fixture = Symbol('fixture');

Expand Down Expand Up @@ -131,23 +131,29 @@ test('passes arguments through', async t => {
t.is(await throttled(fixture), fixture);
});

test('throw if aborted', t => {
const error = t.throws(() => {
const controller = new AbortController();
controller.abort(new Error('aborted'));
pThrottle({limit: 1, interval: 100, signal: controller.signal})(async x => x);
});

t.is(error.message, 'aborted');
});

test('can be aborted', async t => {
const limit = 1;
const interval = 10_000; // 10 seconds
const end = timeSpan();
const throttled = pThrottle({limit, interval})(async () => {});
const controller = new AbortController();
const throttled = pThrottle({limit, interval, signal: controller.signal})(async () => {});

await throttled();
const promise = throttled();
throttled.abort();
let error;
try {
await promise;
} catch (error_) {
error = error_;
}
controller.abort(new Error('aborted'));

t.true(error instanceof AbortError);
const error = await t.throwsAsync(promise);
t.is(error.message, 'aborted');
t.true(end() < 100);
});

Expand Down Expand Up @@ -289,14 +295,15 @@ test('handles simultaneous calls', async t => {
test('clears queue after abort', async t => {
const limit = 2;
const interval = 100;
const throttled = pThrottle({limit, interval})(() => Date.now());
const controller = new AbortController();
const throttled = pThrottle({limit, interval, signal: controller.signal})(() => Date.now());

try {
await throttled();
await throttled();
} catch {}

throttled.abort();
controller.abort();

t.is(throttled.queueSize, 0);
});
Expand Down

0 comments on commit b0eadea

Please sign in to comment.