- 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 iteration, 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
In summary, the Node.js event loop,
- Process and execute code in index.js
- Look for pending timers, OS tasks, 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