What is an event loop in JavaScript?

What is an event loop in JavaScript?

The key to asynchronous programming in JavaScript is the event loop. JS does everything on a single thread, but it gives the impression that it is using multiple threads by using some clever data structures. Let’s investigate the behind-the-scenes action.
The code in JavaScript is run using an event-loop-based runtime model, which also handles incoming events and runs any tasks that have been queued up. Compared to models in languages like C and Java, this one is quite unique.
When I mention that JavaScript runs on a single thread, what exactly is that?
In other words, there is no way for JavaScript code to run in parallel, and the primary thread where it is executed operates in a one-line-at-a-time fashion.

console.log("Before delay");
function delayBySeconds(seconds) {
let start = now = Date.now();
while(now-start < (seconds*1000)) {
now = Date.now();
}
}
delayBySeconds(5);
// Executes after delay of 5 seconds
console.log("After delay");Memory allocation in JavaScript:
- Heap memory: Data stored randomly and memory allocated.

2. Stack memory: Memory allocated in the form of stacks, mainly used for functions.
call stack:
The call stack is in charge of keeping track of upcoming actions. If a function completes successfully, it will be popped from the stack.

function LevelTwo() {
console.log('Inside Level Two!');
}function LevelOne() {
LevelTwo();
}function main() {
LevelOne();
}main();event queue:
New functions are sent to the stack through the event queue. It uses a queue data structure to ensure that operations are sent in the proper order.
Once an asynchronous method is invoked, the request is sent to the browser’s application programming interface. These application programming interfaces (APIs) are native to the browser. In response to a request from the call stack, the API initiates a separate, single-threaded process.
Where does it send the operation? The event queue. Hence, we have a cyclic system for running async operations in JavaScript. The language itself is single-threaded, but the browser APIs act as separate threads.
The event loop facilitates this process; it constantly checks whether or not the call stack is empty. If it is empty, new functions are added from the event queue. If it is not, then the current function call is processed.

Follow me on GitHub: Madhusha Prasad
Comments
Post a Comment