Reputation: 352
The common example of presenting the functionality of setImmediate function in Node JS is the following code
console.log('1');
setImmediate(() => console.log('2'));
console.log('3');
which evaluates to
1
3
2
As far as I know setImmediate callbacks are executed during check
phase of event loop
However I don't understand where fetching new, sequential instruction fits there? Are we guaranteed that Node will fetch and execute console.log('3')
BEFORE executing the check phase and therefore print 3
before 2
? If so - how many such instruction would Node execute before reaching check
phase?
Upvotes: 2
Views: 557
Reputation: 29011
However I don't understand where fetching new, sequential instruction fits there?
No need to fetch anything new because all the instructions have to be loaded already at that point, since we are already in the middle of executing them!
Are we guaranteed that Node will fetch and execute console.log('3') BEFORE executing the check phase and therefore print 3 before 2?
Yes.
If so - how many such instruction would Node execute before reaching check phase?
Infinitely many.
JavaScript is single-threaded* and there nothing can preempt your code (other than a Ctrl+C).
So, the following code will keep outputting 3
in all eternity and never get to 2
**:
console.log('1');
setImmediate(() => console.log('2'));
while (true) {
console.log('3');
}
1
3
3
3
3
... (forever)
Similarly, the following code will for all eternity print 2A
and never get to 2B
:
console.log('1');
setImmediate(() => {
while (true) {
console.log('2A');
}
});
setImmediate(() => console.log('2B'));
console.log('3');
1
3
2A
2A
2A
2A
... (forever)
(The same applies if you were to move the setImmediate(() => console.log('2B'));
inside the first callback instead of putting it below it.)
*: Yes there are worker threads in node.js and service workers in the browser, but they live in their own environments.
**: ...consuming 100% of one CPU core in the process and not reacting to any events or signals, so consider this an example of academic interest only, not something you would ever write in real code.
Upvotes: 4