Skip to content

Commit ce74593

Browse files
committedMar 1, 2023
fix: fast timers and event loop lag
1 parent 2f463fc commit ce74593

File tree

1 file changed

+15
-11
lines changed

1 file changed

+15
-11
lines changed
 

Diff for: ‎lib/timers.js

+15-11
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,15 @@ function onTimeout () {
1313
while (idx < len) {
1414
const timer = fastTimers[idx]
1515

16-
if (timer.expires && fastNow >= timer.expires) {
17-
timer.expires = 0
16+
if (timer.state === 0) {
17+
timer.state = fastNow + timer.delay
18+
} else if (timer.state >= 0 && fastNow >= timer.state) {
19+
timer.state = -1
1820
timer.callback(timer.opaque)
1921
}
2022

21-
if (timer.expires === 0) {
22-
timer.active = false
23+
if (timer.state === -1) {
24+
timer.state = -2
2325
if (idx !== len - 1) {
2426
fastTimers[idx] = fastTimers.pop()
2527
} else {
@@ -53,27 +55,29 @@ class Timeout {
5355
this.callback = callback
5456
this.delay = delay
5557
this.opaque = opaque
56-
this.expires = 0
57-
this.active = false
58+
59+
// -2 not in timer list
60+
// -1 in timer list but inactive
61+
// 0 in timer list waiting for time
62+
// > 0 in timer list waiting for time to expire
63+
this.state = -2
5864

5965
this.refresh()
6066
}
6167

6268
refresh () {
63-
if (!this.active) {
64-
this.active = true
69+
if (this.state === -2) {
6570
fastTimers.push(this)
6671
if (!fastNowTimeout || fastTimers.length === 1) {
6772
refreshTimeout()
68-
fastNow = Date.now()
6973
}
7074
}
7175

72-
this.expires = fastNow + this.delay
76+
this.state = 0
7377
}
7478

7579
clear () {
76-
this.expires = 0
80+
this.state = -1
7781
}
7882
}
7983

0 commit comments

Comments
 (0)