5 scenarios to clear up event loop concepts

JavaScript is single-threaded, so how does it handle asynchronous code without blocking the main thread while it waits for an action to complete? The key to understanding the asynchronous nature of JavaScript is understanding the event loop.

In the browser, the  event loop coordinates the execution of code between the call stack, web APIs, and the callback queue. Node.js, however, implements its own “ Node.js event loop” that is different from the regular “JavaScript event loop.” How confusing!

The Node.js event loop follows many of the same patterns as the JavaScript event loop but works slightly differently, as it doesn’t interact with the DOM but does deal with things like input and output (I/O).

In this article, we’ll dive into the theory behind the Node.js event loop and then look at a few examples using setTimeoutsetImmediate, and process.nextTick. We’ll even deploy some working code to  Heroku (an easy way to quickly deploy apps) to see it all in action.

The Node.js Event Loop

The Node.js event loop coordinates the execution of operations from timers, callbacks, and I/O events. This is how Node.js handles asynchronous behavior while still being single-threaded. Let’s look at a diagram of the event loop below to get a better understanding of the order of operations:

The Node.js event loop’s order of operations

The Node.js event loop’s order of operations (Source:  Node.js docs)

As you can see, there are  six main phases in the Node.js event loop. Let’s briefly look at what happens in each phase:

  • Timers: Callbacks scheduled by setTimeout and setInterval are executed during this phase.
  • Pending callbacks: I/O callbacks that were previously deferred to the next loop iteration are executed during this phase.
  • Idle, prepare: This phase is only used internally by Node.js.
  • Poll: New I/O events are retrieved and I/O callbacks are executed during this phase (except for callbacks scheduled by timers, callbacks scheduled by setImmediate, and close callbacks because those are all handled in different phases).
  • Check: Callbacks scheduled by setImmediate are executed during this phase.
  • Close callbacks: Close callbacks, like when a socket connection is destroyed, are executed during this phase.

It’s interesting to note that process.nextTick isn’t mentioned in any of these phases. That’s because it’s a special method that’s not technically part of the Node.js event loop. Instead, whenever the process.nextTick method is called, it places its callbacks into a queue. According to the docs, those queued callbacks are then “processed after the current operation is completed, regardless of the current phase of the event loop.”

#web-development #nodejs #javascript #programming #node

Understanding the Node.js Event Loop
2.00 GEEK