Java Script Event Looping explained in simple terms.
Javascript is a single-threaded synchronous programming language. It is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, often incorporating third-party libraries.
Assuming that we are familiar with some basic semantics on Javascript, let's move on to our main topic of discussion i.e Event Looping.
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. This model differs from models in other languages like C and Java.
To understand how the event looping works we need to be thorough on the topics below.
- Stack memory
- Heap memory
- Queue
Let us start with the Stack Memory first and will slowly touch upon the other two.
Consider the below example code.
function add20(b) {
const a = 20;
return a + b;
}
function multiplyBy3(x) {
const y = 3;
return add20(x * y);
}
const ma = multiplyBy3(5); // assigns 35 to ma
Order of operations:
- When calling
multiplyBy3
, a first frame is created containing references tomultiplyBy3's
arguments and local variables. - When
multiplyBy3
callsadd20
, a second frame is created and pushed on top of the first one, containing references toadd20's
arguments and local variables. - When
add20
returns, the top frame element is popped out of the stack (leaving onlymultiplyBy3
call frame). - When
multiplyBy3
returns, the stack is empty.
Note that the arguments and local variables may continue to exist, as they are stored outside the stack — so they can be accessed by any nested functions long after their outer part has returned.
Heap Memory is just a random memory allocation for objects. In the above code sample, the function params are stored on the heap memory and removed until the last function reference/frame is removed from the stack.
A queue is a place where JS event looping looks for messages and places them onto the function execution stack whenever the function stack becomes empty. This process is continued until the message queue becomes empty.
For each message in the queue, a stack is loaded with function frames and made empty for the messages in the queue(if there is one).
Event loop
The event loop got its name because of how it’s usually implemented, which usually resembles the:
while (queue.waitForMessage()) {
queue.processNextMessage();
}
queue.waitForMessage()
waits synchronously for a message to arrive (if one is not already available and waiting to be handled).
Thank You so much for reading this and please keep supporting and sharing your love.