Skip to content

Commit e425b7e

Browse files
authored
refactor: simplify async timer logic (#3028)
1 parent b9d3dca commit e425b7e

File tree

2 files changed

+251
-114
lines changed

2 files changed

+251
-114
lines changed

src/utils.ts

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -954,7 +954,7 @@ export function makeInterruptibleAsyncInterval(
954954
): InterruptibleAsyncInterval {
955955
let timerId: NodeJS.Timeout | undefined;
956956
let lastCallTime: number;
957-
let lastWakeTime: number;
957+
let cannotBeExpedited = false;
958958
let stopped = false;
959959

960960
options = options ?? {};
@@ -965,10 +965,8 @@ export function makeInterruptibleAsyncInterval(
965965

966966
function wake() {
967967
const currentTime = clock();
968-
const timeSinceLastWake = currentTime - lastWakeTime;
969-
const timeSinceLastCall = currentTime - lastCallTime;
970-
const timeUntilNextCall = interval - timeSinceLastCall;
971-
lastWakeTime = currentTime;
968+
const nextScheduledCallTime = lastCallTime + interval;
969+
const timeUntilNextCall = nextScheduledCallTime - currentTime;
972970

973971
// For the streaming protocol: there is nothing obviously stopping this
974972
// interval from being woken up again while we are waiting "infinitely"
@@ -986,14 +984,15 @@ export function makeInterruptibleAsyncInterval(
986984
}
987985

988986
// debounce multiple calls to wake within the `minInterval`
989-
if (timeSinceLastWake < minInterval) {
987+
if (cannotBeExpedited) {
990988
return;
991989
}
992990

993991
// reschedule a call as soon as possible, ensuring the call never happens
994992
// faster than the `minInterval`
995993
if (timeUntilNextCall > minInterval) {
996994
reschedule(minInterval);
995+
cannotBeExpedited = true;
997996
}
998997
}
999998

@@ -1005,7 +1004,7 @@ export function makeInterruptibleAsyncInterval(
10051004
}
10061005

10071006
lastCallTime = 0;
1008-
lastWakeTime = 0;
1007+
cannotBeExpedited = false;
10091008
}
10101009

10111010
function reschedule(ms?: number) {
@@ -1018,7 +1017,7 @@ export function makeInterruptibleAsyncInterval(
10181017
}
10191018

10201019
function executeAndReschedule() {
1021-
lastWakeTime = 0;
1020+
cannotBeExpedited = false;
10221021
lastCallTime = clock();
10231022

10241023
fn(err => {

0 commit comments

Comments
 (0)