Tech Talk 01: JavaScript Event Loop
Sadat Rafsanjani
Software Engineer | SaaS Architect | AI Tinkerer | Open-Source Contributor | #Java #Python #AI
For those of us working in JavaScript for a while, we all know about the event loop mechanism. In this talk, we discuss how event loop works. So, without further due, lets get started.
Event Loop
The runtime memory model of JavaScript is called event loop, it is a constantly running process of the JavaScript that monitors the stack and event queue.
The JavaScript runtime model is a bit different from other languages because it is single-threaded.
It has three main components inside it:
1) Heap
2) Stack
3) Event Queue
Heap
Objects are stored in Heap memory. It is an unstructured place where newly created object or instances reside.
Stack
Every time a function call is encountered, that function is placed here. As stack performs in the LIFO (Last In First Out) manner, the latest function call is executed first than popped from the stack. If it encounters any blocking method call (API service call, timer etc.), that part is immediately moved to the browser Web API part.
Event Queue
An internal message queue for JavaScript.
Web API
This comes with web browser. Here blocking method calls are placed. First the method is executed here than passed to the event queue of JavaScript. Event queue is nothing but
a message queue. The message queue waits util the JavaScript runtime is emptied. Once the stack is empty the Event Loop deques the Event Queue and places the function in the stack.
领英推荐
Example:
Lets consider the following code:
function foo(){
console.log("Start");
setTimeout(function(){
console.log("1 2 3...";)
}, 2000);
console.log("This is the end!");
}
foo();
So, what is happening here? foo() is called. Inside the foo(), there are three statements. Lets see JavaScript runtime handles that.
In the initial stage, the heap is populated with objects. Then the stack is populated in the LIFO manner. It starts to execute the function calls one by one and pop them.
When it encounters the setTimeout(), it is immediately removed from Stack and placed to Web API. Then Stack is emptied. In the meantime, setTimeout() is also completed and is placed in the Event Queue.
The Event Loop monitors the stack and Event Queue continuously. If it finds anything in the queue then it checks whether Stack is empty or not. If empty, message is moved from Event Queue to the Stack.
In this manner, Stack continues to perform. Finally, Stack is cleared and program execution finishes.
In fine we can conclude that, Event Loop is noting but a background process which monitors and performs memory management.