I have the following code to demonstrate the problem:
let count = 5;
while (count--) {
setTimeout(() => {
console.log('timeout');
process.nextTick(() => {
console.log('tick');
});
}, 0);
}
const largeNumber = 20000;
for (let i = 0; i < largeNumber; i += 1) {
for (let j = 0; j < largeNumber; j += 1) {
}
}
The result that I expect is as follows:
timeout
tick
timeout
tick
timeout
tick
timeout
tick
Since the event loop checks the queue timeouts, it detects the first callback setTimeout, starts it, and checks the queue nextTickafter. And for further callbacks setTimeouthe has to do the same.
But I get the following output:
timeout
timeout
timeout
timeout
timeout
tick
tick
tick
tick
tick
Why?
source
share