There is an example in the explanation of event loop on the official website of Node.js. When setTimeout is executed, the callback queue corresponding to the timer phase is not empty, right? so why can the event loop continue to the poll phase? The official website says that someAsyncOperation executes in 95ms, why does the callback function of someAsyncOperation execute before the callback of setTimeout?
const fs = require('fs');
function someAsyncOperation(callback) {
// Assume this takes 95ms to complete
fs.readFile('/path/to/file', callback);
}
const timeoutScheduled = Date.now();
setTimeout(() => {
const delay = Date.now() - timeoutScheduled;
console.log(`${delay}ms have passed since I was scheduled`);
}, 100);
// do someAsyncOperation which takes 95 ms to complete
someAsyncOperation(() => {
const startCallback = Date.now();
// do something that will take 10ms...
while (Date.now() - startCallback < 10) {
// do nothing
}
});
After someAsyncOperation is executed, it takes 95ms to call the callback and this moment, setTimeout is still not yet ready be called.(It takes 100ms)
When the callback is called, it occupies the queue because it is still running and it takes 10ms.
After the callback is running for 5ms more, setTimeout is ready but the queue is still not empty, thus it cannot be executed.