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

Support AbortController #53

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
45 changes: 32 additions & 13 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 @@ -43,6 +32,36 @@ export type Options = {
*/
readonly strict?: boolean;

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

@example
```
import pThrottle from 'p-throttle';

const controller = new AbortController();
liuhanqu marked this conversation as resolved.
Show resolved Hide resolved

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`.

Expand All @@ -61,8 +80,8 @@ export type Options = {
});

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

await throttled();
await throttled();
Expand Down
16 changes: 5 additions & 11 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,4 @@
export class AbortError extends Error {
constructor() {
super('Throttled function aborted');
this.name = 'AbortError';
}
}

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,15 +84,16 @@ export default function pThrottle({limit, interval, strict, onDelay}) {
});
};

throttled.abort = () => {
signal?.throwIfAborted();
signal?.addEventListener('abort', () => {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You need to remove this listener when the function is done, so not to create event listener leaks.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seem to have no way to know that the function is done?

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);
};
}, {once: true});

throttled.isEnabled = true;

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
10 changes: 6 additions & 4 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,12 @@ 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
liuhanqu marked this conversation as resolved.
Show resolved Hide resolved

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`.

##### onDelay

Type: `Function`
Expand Down Expand Up @@ -119,10 +125,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