Skip to content

Commit

Permalink
Call setTimeout only when execution is delayed (#46)
Browse files Browse the repository at this point in the history
  • Loading branch information
dormeiri authored Dec 5, 2023
1 parent 3dffe70 commit a2c2a66
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
10 changes: 7 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,13 @@ export default function pThrottle({limit, interval, strict}) {
queue.delete(timeoutId);
};

timeoutId = setTimeout(execute, getDelay());

queue.set(timeoutId, reject);
const delay = getDelay();
if (delay > 0) {
timeoutId = setTimeout(execute, delay);
queue.set(timeoutId, reject);
} else {
execute();
}
});
};

Expand Down
9 changes: 8 additions & 1 deletion test.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ test('main', async t => {
test('queue size', async t => {
const limit = 10;
const interval = 100;
const delayedExecutions = 20;
const throttled = pThrottle({limit, interval})(() => Date.now());
const promises = [];

Expand All @@ -34,7 +35,13 @@ test('queue size', async t => {
promises.push(throttled());
}

t.is(throttled.queueSize, limit);
t.is(throttled.queueSize, 0);

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

t.is(throttled.queueSize, delayedExecutions);

await Promise.all(promises);

Expand Down

0 comments on commit a2c2a66

Please sign in to comment.