Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fast timers and event loop lag #1977

Merged
merged 1 commit into from
Mar 3, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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) {
ronag marked this conversation as resolved.
Show resolved Hide resolved
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