Skip to content

Commit

Permalink
fix: fast timers and event loop lag (nodejs#1977)
Browse files Browse the repository at this point in the history
  • Loading branch information
ronag authored and crysmags committed Feb 27, 2024
1 parent 84b2ddd commit b39cce9
Showing 1 changed file with 15 additions and 11 deletions.
26 changes: 15 additions & 11 deletions lib/timers.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,15 @@ function onTimeout () {
while (idx < len) {
const timer = fastTimers[idx]

if (timer.expires && fastNow >= timer.expires) {
timer.expires = 0
if (timer.state === 0) {
timer.state = fastNow + timer.delay
} else if (timer.state > 0 && fastNow >= timer.state) {
timer.state = -1
timer.callback(timer.opaque)
}

if (timer.expires === 0) {
timer.active = false
if (timer.state === -1) {
timer.state = -2
if (idx !== len - 1) {
fastTimers[idx] = fastTimers.pop()
} else {
Expand Down Expand Up @@ -53,27 +55,29 @@ class Timeout {
this.callback = callback
this.delay = delay
this.opaque = opaque
this.expires = 0
this.active = false

// -2 not in timer list
// -1 in timer list but inactive
// 0 in timer list waiting for time
// > 0 in timer list waiting for time to expire
this.state = -2

this.refresh()
}

refresh () {
if (!this.active) {
this.active = true
if (this.state === -2) {
fastTimers.push(this)
if (!fastNowTimeout || fastTimers.length === 1) {
refreshTimeout()
fastNow = Date.now()
}
}

this.expires = fastNow + this.delay
this.state = 0
}

clear () {
this.expires = 0
this.state = -1
}
}

Expand Down

0 comments on commit b39cce9

Please sign in to comment.