Node.T. JS Event Loop is a concept that seems difficult to understand first. But as any seemingly complex article, the best way to understand this is often through resemblance.
In this article, you will learn how working managers, busy waiters, and train stations can help bring the basic concept of event loop home. If you are working with the node, you will need to understand how the event loop works, as it is at the root of today’s most powerful applications.
The table of content
Provisions
Following this article without interruption Lt IT, if you are familiar with the following concepts will help:
Basic understanding of JavaScript: Node. The JS Java runs on the script, so you will need to understand the variable, functions and flow of control.
Familiar with the basics of node.t JS: Easy script with the node and requires module.
Some exhibit of non -ridiculous patterns: Knowing what samples
setTimeout()DoSome familiarity with the basic CPU concepts (core and threads): This will help you better understand harmony and harmony.
Aware of promises and async/wait: This is optional and is not in need, but will be helpful.
What are the synagogue and unprecedented codes?
When Node Dot writes code for JS applications, there are two different ways that can operate: synchronization (synchronization) and Asynconus (Async). Symbolized code is referred to as Block Because when it runs, no other code runs until the process is complete.
The imitation for this is a busy restaurant. Make a photo of a waiter that refuses to wait on other tables until he is presenting on the table he has received his orders and started eating. When the food is being prepared, the waiter waits for nothing and when you take your order to your table when they are completely finished with the previous table. Needless to say, the waiter cannot get any excellent tip of this service.
This is a synchronized code. Unless it is complete, it prevents the implementation of other processes. You can see how it works in the example below:
const syncWaiter = (name) => {
console.log(`${name} attends to tables pretty slowly.`);
};
syncWaiter("Devin");
console.log("At least all the orders are correct!");
The aforementioned code will be run in order, in order it appears.
Contradictory code, unlike the synchronized code, does not stop all other processes until one task is implemented – rather, it moves forward to perform other tasks, while a long process in the background.
Using the imitation of our waiter, in this case the waiter will order from a table, order in the kitchen, and when it is being prepared, your order also proceeds to your desk. In this way, the waiter is able to ensure that a process takes a little longer than the rest. See the example below:
const asyncWaiter = (name) => {
setTimeout(()=> {console.log(`${name} attends to tables pretty quickly.`)}, 3000)
};
asyncWaiter("James");
console.log("Wow! All the tables are attended to in a short time.");
Unlike synchronization code, this code runs the function asyncWaiter() – But the callback inside the function executes later. When the period passes, the result is shown on the screen. This is why conflicting programs are referred to as Non -blocking They do not stop the program, but move from one available work to another.
The above code returns the following:
Wow! All the tables are attended to in a short time.
James attends to tables pretty quickly.
This print order occurs because of how The loop of the event Management of tasks: harmony console.log() It comes after asyncWaiter() Immediately runs, while the skimmer callback is inside asyncWaiter() (Fantasy setTimeout) There is a schedule for running later. If you don’t understand it yet, don’t worry because I will break it in detail soon.
What does harmony and harmony mean
Node. JS is single -thread, but often because of this the appearance of a multi -thread environment, which is why it handles harmony and harmony. A thread is the only series of directives implemented by the CPU. Think about it as a waiter named James in a restaurant.
If James handle numerous tasks at the same time and quickly, a viewer outside the restaurant looks at the number of users going out of the restaurant and can assume that there are a ton of waiters offering tables. In fact, James only handles his actions seriously.
Before understanding the concept of the event loop, it is good to understand what harmony and harmony is, because they help explain it.
Harmonious in nod dot j
Harmony means many processes at the same time. In imitation of the waiter, it is like James as they perform different things, though not simultaneously. For example, he could take an order from a table and, wait for food, request that extra salt be provided to another table. When the salt is on its way, it uses the time to read the bill on the third table.
The important idea is that James never sits useless – he works on other tasks while waiting for someone to end. If this is a terrible thing like Ansynchronous Programming, this is the reason that serious code is the only way to get harmony.
Other methods of harmonizing harmony are multi -threading on the same CPU core and coretines that are just functions that prevent their execution later to resume.
Harmonious in nod dot j
On the other hand, parallel also means to run multiple works at the same time – but instead of taking action at the same time, they are hanged at the same time. In this case, the restaurant’s manager has decided to hire several waiters and each table has a waiter that is taking the order at the same time.
Coordination can be achieved using multiple threading on several CPU core. In this setup, threads share the same memory and go simultaneously using clusters that walk freely – each with their own memory space. Here is a clear example of harmony using worker_threads Module:
const { Worker} = require('worker_threads');
new Worker('./worker.js');
new Worker('./worker.js');
new Worker('./worker.js');
console.log("Main thread keeps running in the process...");
The aforementioned code produces three workers in parallel to the multi -core machine. It does not stop the main thread that keeps moving, which allows every worker to perform his work freely. worker.js There may be an easy file to perform any task. In this case, it easily logs a message on the screen:
console.log("This worker thread is running here!");
Note that argument for Worker The Constructor may have any file path, and the order in which they are implemented does not depend on the order that they appear in the code. Every worker runs freely from others and walks in parallel.
Coordination and harmony allows node Jet J (which is the sole thread) to manage multiple tasks simultaneously. Understanding these concepts leads to the event’s loop, which shows how the Node.com manages how to implement the code by implementing the code in a single thread environment.
What is the loop of the event?
The event Loop Node does the sound of the events in the JS environment. It essentially hears for actions and then acts on tasks or output values.
To better understand how it works, your node. The JS environment can create a picture as a high -speed organization and an event loop as a more working manager who refuses to hire a personal assistant. The manager oversees the operations of the entire office, and it has a dedicated desk that contains whatever work he is doing at this particular time. Let’s call this desk Call steak.
The call stack contains whatever action or work is done in which Node Dot J is currently working. When the input is listed or the code is written to do something, this call goes into the stack and is processed.
The setting in which this process is important is important, because the synchronized code makes it on the call stack before the unmanageable code. You can ask what is the contradictory code? This call goes into something known as the first call back row before it is finished on the stack.
The call back row is a lineup of baseless tasks that make it only in the call stack when the stack is empty. You can think of it as a file cabinet in the office, where a special team of workers under the manager is processed by a unprecedented code until the manager’s desk is cleaned. The manager only leads to the cabinet when they handle all the harmony work on the call stack. This special team that handles the unprecedented code such as callbacks and Async/Waiting are node APIs or web apis.
Node or Web APIS process unreasonable code. When the code comes, it is processed and then the call is placed in the back row to pick up the loop and go to the call stack. But there are some contradictory tasks that are preferred. It is known as microtosics, such as promises.
Microtasics are given special priority and is lined up in a special microtosco que. The call back row is usually checked before checking. If nothing is present, the event loop calls backback checks but if there is some work like process.nextTick()This immediately. It is handled. Macrootasics consist of tasks that are regularly scheduled and handled by the event loop only after the treatment of microtasics. setTimeout() And setInterval().
So as you can see, the loop of the event is basically what seems – a loop. It is watching the events and handles tasks on the basis of a priority schedule.
One thing to note is, even in the call back row and microtasic row, there are steps. For example, the event loop has to handle some of the tasks in the same category in front of others. This is the place where the stages of the loop come.
The stages of the event loop
Through imitation, the event loop is equivalent to a manager that regularly examines the status of projects and tasks at intervals. In this case, they have a special schedule for examining the status of the projects. Some projects or works prefer others, and the manager has to see them in a fixed order.
You can also imagine the stages of the event loop as a train from the station to the station. It starts from one place and moves to others in a particular order until it is complete, then starts the journey again. This arrangement determines which tasks are executed in front of others.
The stages of the event loop are in the sequence:
Stage of timers: This step processes this
setTimeout()AndsetInterval()Callbacks after the period. The event loop starts from here, like the first train travel station.Stage of pending Callbacks: This system is level callbacks, which test the timers phase after operation.
Voting Phase: This phase handle the input/output (I/O) events and implement the callbacks. In the absence of callbacks, the event loop awaits new people here.
Check Step: This step comes into process
setImmediate()CallbacksNear Callbacks: This phase is related to the implementation of close events such as the closure of the socket.
These callback events are checked in order and run accordingly, so if setTimeout() And setImmediate() Are in the same code, setTimeout() First runs until the “train” says, in the loop’s pool phase so that setImmediate() Runs first setTimeout().
You can describe it with the example of the following:
const fs = require('fs');
fs.readFile('trainMap.txt', () => {
setTimeout(() => {
console.log("Train takes off");
}, 0);
setImmediate(() => {
console.log("Oops! Immediate halt! There's a cat on the tracks!");
})
});
You see in the code given above that the callbacks are contradictory. Remember that the event awaits new callbacks in the loop pool phase. What does it mean fs.readfile() There is a callback, it takes action in the voting phase.
setTimeout() Is ready to run in the timers phase but the event loop proceeds in the check phase (which comes next) where setImmediate() Is hanged. That’s why setImmediate() Runs first setTimeout() In this case, the event’s loop continues from the check phase to the nearest stage, from the timers phase, the cycle repeats the cycle.
This shows why you see the output hidden on the screen:
Oops! Immediate halt! There's a cat on the tracks!
Train takes off
This makes it clear how the event loop enforces the execution order in different stages, ensuring that the Snookynus operation runs in the right order.
Conclusion
The loop of the Node.DS event sometimes looks mysterious, but it is not really as complicated as it seems before. In the basic part of it, it is really the only engine that ensures that Javascript can handle a number of tasks without frozen.
In this article, you have learned about how to help synchronizing and contradictory codes, harmony, harmony, and how these concepts help explain the stages of event loop and event loop. Understanding how they work gives you the confidence to write non -free codes without fear, debugged in a more effective manner, and appreciate the ability to handle node Dot JS harmonious tasks.