From 4e4c72b5e61e2b5261f5286d257e934291060fa4 Mon Sep 17 00:00:00 2001 From: Mathias Buus Date: Tue, 1 Oct 2024 20:10:17 +0200 Subject: [PATCH] Fix `setImmediate()` not triggering the timer if idle (#2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Kasper Isager Dalsgarð --- index.js | 8 ++++++++ test/immediate.js | 12 ++++++++++++ 2 files changed, 20 insertions(+) diff --git a/index.js b/index.js index efd5107..57d8261 100644 --- a/index.js +++ b/index.js @@ -251,6 +251,7 @@ function ontimer () { function onimmediate () { const now = Date.now() + const timerRunning = queue.length > 0 let uncaughtError = null @@ -267,6 +268,13 @@ function onimmediate () { tick() + // some reentry wants the timers to start but they are not, lets start them + if (!timerRunning && queue.length > 0) { + const l = queue.peek() + nextExpiry = l.expiry + updateTimer(l.ms) + } + if (uncaughtError !== null) { throw uncaughtError } diff --git a/test/immediate.js b/test/immediate.js index 8a2e7d3..abed1bf 100644 --- a/test/immediate.js +++ b/test/immediate.js @@ -125,3 +125,15 @@ test('setImmediate following setTimeout', async function (t) { clearTimeout(timer) }) + +test('setImmediate that triggers setTimeout', async function (t) { + t.plan(2) + + timers.setImmediate(() => { + t.pass('immediate triggered') + + timers.setTimeout(() => { + t.pass('timeout triggered') + }, 20) + }) +})