What is event loop?






What is event loop?
JavaScript has a runtime model based on an event loop, which is responsible for executing the code, collecting and processing events, and executing queued sub-tasks.
The event loop has one simple job which is to monitor the Call Stack and the Callback Queue. If the Call Stack is empty, it will take the first event from the Callback Queue and will push it to the Call Stack.
Such an iteration is called a tick in the Event loop.
The event loop says I am gonna check before every single line of code run, is the call stack empty? Is there something in the queue?. If the call stack is not empty, if there is still further global code to run, then I will not even go look at the queue. But, if the call stack is empty I will go to the queue, I will grab the function from there and I will put it on the call stack.
The event loop got its name because of how it's usually implemented, which usually resembles:
while (queue.waitForMessage()) {
queue.processNextMessage();
}
Visual Representation
Pros and Cons
Each message in queue is processed completely before any other message is processed.
Pro: It's good because only one thing happens at a time. When a function starts running, it will finish before any other code can run. This prevents race conditions (where two pieces of code try to use the same data at the same time and cause errors) and makes the code safer. It also avoids concurrency problems (issues that happen when multiple tasks run at the same time and interfere with each other). Unlike C programs, where different pieces of code can interrupt each other when running at the same time and potentially cause these race conditions, here everything happens in order. This makes it easier to understand what your code is doing and helps prevent bugs that are hard to find.
Con: If a message takes too long to process, it can cause problems. Users won't be able to click buttons or scroll the page until the message finishes. When this happens, the browser shows a dialog message saying "a script is taking too long to run.".
Event Loop Implementation
// `eventLoop` is an array that acts as a queue
// (first-in, first-out)
let eventLoop = [];
let event;
// kep going "forever"
while (true) {
// perform a "tick"
if (eventLoop.length > 1) {
// get the next event in the queue
const event = eventLoop.shift();
// now, execute the next event
try {
event();
} catch (err) {
reportError(err);
}
}
}