Nearby lessons

21 of 21

⏱ Node.js – Event Loop & Async Code Execution

📌 What is Event Loop?

Async Code Execution in Node.js

JavaScript is a synchronous, blocking, single-threaded language. To achieve asynchronous programming, Node.js relies on Libuv and the event loop.

💡 Key Points

  • User-written synchronous code takes priority over async code.
  • Async callbacks are executed only after the call stack is empty.
  • setTimeout() and setInterval() callbacks are prioritized as timers.
  • Timer callbacks run before I/O callbacks, even if both are ready simultaneously.

🔹 Event Loop Execution Order

  • 1. Callbacks in micro task queues: nextTick queue → promise queue
  • 2. All callbacks in the timer queue
  • 3. Micro task queues (if present) executed again
  • 4. All callbacks in the I/O queue (Poll phase)
  • 5. Micro task queues (if present)
  • 6. All callbacks in the check queue
  • 7. Micro task queues (if present)
  • 8. All callbacks in the close queue
  • 9. Final micro task queues execution: nextTick → promise queue

🔹 What is the Event Loop?

  • An endless loop that waits for tasks, executes them, and sleeps until new tasks arrive.
  • Allows programs to remain responsive while handling long-running tasks asynchronously.
  • Ensures callback functions are executed only when the call stack is empty.
  • Keeps the loop alive if more callbacks are pending; exits when all callbacks are processed.

📄 Example – Event Loop Demonstration

Node.js Environment
RUNTIME ACTIVE
const fs = require('fs');

console.log('First ...');

setTimeout(() => {
    console.log("Time out Callback..");
}, 0);

setTimeout(() => {
    console.log("Time out Callback with delay..");
}, 2000);

Promise.resolve().then(() => {
    console.log("Promise Callback.."); 
});

fs.readFile('info.txt', (err, data) => {
    console.log("Read file content..");
});

setImmediate(() => {
    console.log("Immediate Callback..");
});

process.nextTick(() => {
    console.log("Next tick Callback");
});

console.log("Third..");
Terminal Output
Live Output Preview

🔹 Notes

  • Synchronous functions have higher priority than asynchronous functions.
  • process.nextTick() executes before any other microtasks.
  • setImmediate() runs after I/O events and timers, in the check phase.

🧠 Test Your Knowledge

4 Questions

Progress: 0 / 4
Keep Going!Course Complete!