From 70ac3f6f64328088ce9d4225b1597636f4b6b856 Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Wed, 1 Mar 2023 08:25:46 +0100 Subject: [PATCH] fix: fast timers and event loop lag --- lib/timers.js | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/lib/timers.js b/lib/timers.js index 4f4fcea4413..5782217a0e0 100644 --- a/lib/timers.js +++ b/lib/timers.js @@ -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 { @@ -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 } }