Can a setImmediate() function scheduled in an I/O callback recalculate timeout for other I/O notifications?
Asked Answered
O

1

1

There is the poll stage of the Node js's event loop. Its aim is to blockingly wait for I/O notifications and then execute needed callbacks. A timeout time of the waiting is calculated before entering this stage. If there were operations scheduled through setImmediate than the timeout is set at 0, if timers took place than timeout is set with a view of them and if there are no such impediments the blocking would continue "forever".

What will happen if the timeout is initially set at "infinity" and an I/O callback schedules a function with setImmediate or setInterval? Would the timeout be recalculated immediately or only after the I/O queue got empty (in a next loop iteration)?

So if we wait for two launched asynchronous opearations with callbacks A and B and after receiving an I/O notification A is executed and it in turn schedules some C function with setImmediate what the function would execute first B or C?

Ochs answered 24/1, 2021 at 11:9 Comment(0)
A
0

Note that for some of the more common asynchronous API with timer support (eg. the select() or kqueue() system call) a timer value of zero (0) represents the value of infinity so you cannot implement a function like setImmediate() or nextTick() the usual way by calculating the next timeout value and calling the asynchronous API. Instead all setImmediate() or nextTick() callbacks must be called synchronously before calling the asynchronous API.

Therefore, since C is a callback to setImmediate() it will be called before we re-enter the event loop to wait for B to fire.

So if A and only a gets triggered then the sequence of function calls would be: A and C.

But if A and B happens at the same time the sequence of function calls would be: A, B, C.

Note that I said A and C and not A, C, B because we didn't say B gets triggered. For all I know B will only get triggered 8 months from now or even never.

But if A gets triggered and 1 millisecond later B happens then the sequence of function calls would be: A, C, B


Is it possible for two events to happen in the same event loop? Generally yes. If it's network I/O it is unlikely because IP packets are serialized but it can still happen especially if you have a machine with multiple network cards. If it's graphical events like DOM updates then two things happening in the same event loop is quite common eg: both page resize and content reflow can happen at the same time especially with responsive CSS using media query where page resize can trigger content reflow.

Adversative answered 24/1, 2021 at 17:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.