Skip to content

Commit

Permalink
fix: fast timers and event loop lag
Browse files Browse the repository at this point in the history
  • Loading branch information
ronag committed Mar 1, 2023
1 parent 2f463fc commit edac9a4
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.expires === 0) {
timer.expires = fastNow + timer.delay
} else if (timer.expires >= 0 && fastNow >= timer.expires) {
timer.expires = -1
timer.callback(timer.opaque)
}

if (timer.expires === 0) {
timer.active = false
if (timer.expires === -1) {
timer.expires = -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.expires = -2

this.refresh()
}

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

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

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

Expand Down

0 comments on commit edac9a4

Please sign in to comment.