- Non-blocking (asynchronous) I/O
- Cross-platform runtime environment
The event loop is the core player for maintaining these properties and makes Node.js a faster runtime.
Anytime we run a node.js program, it creates one thread and then runs all of our codes inside that thread.
The event loop acts as a control structure to decide, what our one thread should be doing at one given time.
When we run a js file, Node first takes all the codes and executes them. This is the moment we enter the event loop.
Every time the event loop executes a cycle, in the Node.js world, it is called tick.
Every time the event loop is about to execute, Node quickly checks whether the loop should proceed or not for another iteration. If node decides not to run more iterations, the program closes and we go back to the terminal.
The event loop continues to the next iteration when
shouldContinue method returns true.
When node first goes through the code first time, it detects
Every single iteration of an event loop is called a tick. In pseudo-code, it looks as follows
This handles the long-running process and lets the call stack know it is done with some process and that data is ready.
This web API handle the fetch API, dom events, and long-running process like the set-timeout or set-interval method. Even this web API can be used as caching or runtime database.
So when a long-running async process came up in the call stack, it pass that task to the web API.
Web-API handles the task in the background and put the completed task in the call-back queue.
The event loop always checks if the call stack is empty or not. If it is empty then it put the completed task from the call-back queue into the call stack.
In summary, the Node.js event loop,
- Process and execute code in index.js
- Look for pending timers, OS tasks, and pending operations. If no tasks exist, exit.
- Run setTimeout's, setInterval's
- Run callbacks for OS tasks and thread pools pending stuff
- Pause and wait for stuff done
- Run setImmediate functions
- Handle close events
- Return to step 2