This article is suitable for Node JS developers that want to know exactly how node event loop operates.
I will explain the exact order of operations in the event loop step by step.
But first, a few words on what is the event loop.
By definition (https://nodejs.org) the event loop is what “allows Node.js to perform non-blocking I/O operations — despite the fact that JavaScript is single-threaded — by offloading operations to the system kernel whenever possible”.
What it actually does is to pick an event from the event queue and push its callback to the call stack, In our case, the call stack is a stack of functions.
You can imagine how easy it is to write a block programming code just by adding a complex calculations or long “for loops” for example. Node event loop helps us to avoid just that.
Let’s take setTimeout() as an example of a simple function with a callback, to demonstrate the flow between the main players and the event loop.
const slowOperation = () => {
setTimeout(() => {
console.log('long operation completed')
}, 3000)
}slowOperation()
Follow our function execution steps 1–4:
- slowOperation() invoked and added to the stack
- setTimeout() invoked and added to the stack
- setTimeout() instantiate Node timer
→ setTimeout() pop from the stack
→ slowOperation() pop from the stack (*Call stack is now empty).
4. Node timer is completed (step 3) and queued its callback to the event queue.
→ The event loop monitors both the event queue and the call stack. once the there are events in the event loop and the call stack is empty it pushed the callback to the call stack.
Follow our function execution steps 5 and 6:
5. callback “cb” pushed to the stack
6. console.log pushed to the stack
→ console.log() prints ‘long operation completed’ and pop from the stack
→ “cb” pop from the stack (*Call stack is empty)
And thats it, the event loop job is pretty simple — Push callbacks from the event queue to the call stack.
I hope that understanding how the event loop works, helps you understand better node event-based concurrency model.
If you looking for more information about how to avoid block programming code in Node, I recommend you to check out this article, https://nodejs.org/en/docs/guides/dont-block-the-event-loop/.
Have a good one :)