Open ckcr4lyf opened 1 year ago
Caused failure for #48159
The subject issue says setTimeout() & setInterval()
but looks like it's really about setTimeout() & setImmediate()
?
Correct, my bad. Let me fix it.
The timer module only cares about relative time, so node chooses to use gethrtime()
as the time source, while the Date.now()
is using gettimeofday()
. If the clock under the gethrtime()
goes enough slower than the one under gettimeofday()
, then 'IMMEDIATE' may print first.
setTimeout(() => {
console.log('TIMEOUT')
}, 1);
const now = Date.now();
while (Date.now() - now < 2);
setImmediate(() => {
console.log('IMMEDIATE');
})
Test
test-timers-immediate-queue.js
Platform
Linux x64
Console output
Build links
Additional information
This seems to be some kinda potential race condition between
setTimeout()
andsetImmediate()
?For the following code, it seems
TIMEOUT
orIMMEDIATE
either could be printed first, since over a few runs the order will flip.However on my machine, the following code will always result in
TIMEOUT
being printed first - the while loop strategy is what the test usesI was wondering: is it possible due to some conditions on the host system, for
IMMEDIATE
to print beforeTIMEOUT
in the second case?I do not know much about the Event Loop internals, but from some rough reading,
setTimeout()
will put calbacks in the timers queue,setImmediate()
in the I/O queue, and the timers are always checked first (https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick)But if in the first case (
setTimeout
without while waiting loop) it is non-predictable, I wonder if there are other factors at play, which make the test flaky.