Skip to content

Commit

Permalink
Merge pull request #2 from dormeiri/onDelay_arguments
Browse files Browse the repository at this point in the history
On delay arguments
  • Loading branch information
dormeiri authored Aug 12, 2024
2 parents 0ed167a + 01474f0 commit 9c247d8
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 20 deletions.
24 changes: 12 additions & 12 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,25 +55,25 @@ export type Options = {
const throttle = pThrottle({
limit: 2,
interval: 1000,
onDelay: () => {
console.log('Reached interval limit, call is delayed');
onDelay: (param1, param2) => {
console.log(`Reached interval limit, call is delayed for ${param1} ${param2}.`);
},
});
const throttled = throttle(() => {
console.log('Executing...');
const throttled = throttle((param1, param2) => {
console.log(`Executing with ${param1} ${param2}...`);
});
await throttled();
await throttled();
await throttled();
//=> Executing...
//=> Executing...
//=> Reached interval limit, call is delayed
//=> Executing...
await throttled(1, 2);
await throttled(3, 4);
await throttled(5, 6);
//=> Executing with 1 2...
//=> Executing with 3 4...
//=> Reached interval limit, call is delayed for 3 4
//=> Executing with 5 6...
```
*/
readonly onDelay?: () => void;
readonly onDelay?: (...arguments_: readonly any[]) => void;
};

/**
Expand Down
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export default function pThrottle({limit, interval, strict, onDelay}) {
if (delay > 0) {
timeoutId = setTimeout(execute, delay);
queue.set(timeoutId, reject);
onDelay?.();
onDelay?.(...arguments_);
} else {
execute();
}
Expand Down
17 changes: 10 additions & 7 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -402,25 +402,28 @@ test('manages rapid successive calls', async t => {
});

test('onDelay', async t => {
let delayedCounter = 0;
const delayedIndices = [];
const limit = 10;
const interval = 100;
const delayedExecutions = 20;
const onDelay = () => delayedCounter++;
const throttled = pThrottle({limit, interval, onDelay})(() => Date.now());
const onDelay = (keyPrefix, index) => {
delayedIndices.push(keyPrefix + index);
};

const throttled = pThrottle({limit, interval, onDelay})((_keyPrefix, _index) => Date.now());
const promises = [];

for (let index = 0; index < limit; index++) {
promises.push(throttled());
promises.push(throttled('a', index));
}

t.is(delayedCounter, 0);
t.deepEqual(delayedIndices, []);

for (let index = 0; index < delayedExecutions; index++) {
promises.push(throttled());
promises.push(throttled('b', index));
}

t.is(delayedCounter, delayedExecutions);
t.like(delayedIndices, {0: 'b0', 1: 'b1', 19: 'b19', 20: undefined});

await Promise.all(promises);
});

0 comments on commit 9c247d8

Please sign in to comment.