nodejs: setTimeout and IO(POLL) is showing inconsistency

Viewed 104

I have this piece of code:

// * Run this snippet of code multiple times

const fs = require('fs');

setTimeout(() => {
    console.log('timer');
});

fs.readFile('', 'utf-8',(err, data) => {
    console.log('io');
});

setImmediate(() => {
    console.log('check');
});

On running the above mentioned code for multiple times. I'm getting different outputs. Output

Result 1 Somethimes I'm getting
timer
io
check

Result 2 and other times. I'm getting
io
check
timer

Can anyone please clarify what is going on here? I was expecting Result 1.

2 Answers

That has to do with how the event loop picks up things to do when more than one thing is available. Here you can find a good explanation.

If you really want to set that order, try async/await or calling fs.readFile() inside the setTimeout() callback.

Based on node.js event loop documentation, a setTimeout is called which sets a minimum amount of time to wait until the function is executed. Next you start an asynchronous file read. Then the polling phase of the event loop will begin. The polling phase has a queue of callback functions to complete. If the file read is not complete, it's callback function (the console.log) will not be put in the polling queue. The polling phase will instead wait for the timer to meet the minimum threshold time and then loop back to the timer callback execution phase. Since your setTimeout is set to zero ms, the polling phase will usually exit and complete the timer callback (console.log) first and then go back to polling for the file read to finish. This is why sometimes your setTimeout completes first if your underlying operating system delays the file read, or the file read completes first if the operating system delays the setTimeout. setImmediate will always happen immediately after the polling (io) phase.

Related