Why does a while loop blocks the event loop?

var flag = true;
setTimeout(function(){
    console.log('timeout completed');
    flag = false;
}, 1000);
while(flag) {
}
console.log('done');

How Node.js process this program?

  1. flag variable declaration will be placed in call stack and it will be initialized to true.
  2. setTimeout() function call will be placed in call stack.
  3. Node.js start the timer and schedules a timer event for 1 second. The callback function will be placed in MessageQueue after 1 second.
  4. Node.js continues further and starts executing the while loop
  5. After 1 second, Node.js places the callback function of setTimeout in MessageQueue which gets executed when is no statements exists in the call stack
  6. As the variable value never becomes false, the while loop never exit
  7. Due to this event loop is blocked, it will not be able to execute statements in MessageQueue

The loop gives priority to the call stack, and it first processes everything it finds in the call stack, and once there’s nothing in there, it goes to pick up things in the message queue.

nodejs.dev

A programmer need to pay attention on how he writes the code and avoid writing code that can block the thread, like the above infinite loop.

See also  Read File Synchronously and Asynchronously (Blocking and Non-blocking ways)