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

Example05
Loading editor…

🔹 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