Skip to main content

Command Palette

Search for a command to run...

How Works Event Loop?

Updated
2 min read
How Works Event Loop?

Event Loop:-

Javascript has a runtime model-based event loop, which is responsible for executing code. Event Loop monitor CallStack and Callback Queue. if CallStack is empty event loop takes an event from Callback Queue and sends the event to CallStack for execution.

ek7ji4zrimozpp2yzk0a.webp

let's understand How it works Event loop?

Basically, Javascript is a single-threaded programing language, it has only one call stack, which means it can be one thing at a time. and this call stack is inside the javascript engine and all the code of js is executed inside the call stack.

Execution:- Execution is not possible without a memory heap and call stack.

Memory Heap:- A memory Heap is a place where all the memory are stored (like- variable and functions).

Garbage Collector:- whenever some functions are not used that time collects all the garbage and swipes it with help of the swipe and mark algorithms.

Difference between stack and heap memory in Java.gif

CallStack:-

The main job of CallStack is to all the Javascript code executed inside the call stack. CallStack does not wait for anything, if anything comes inside the call stack, it quickly executes.

gif4.gif

Web APIs:-

we have some web APIs and these web APIs are not part of the Javascript. web APIs are part of the Browser.

Some Web APIs are:-

  • SetTimeout
  • DOM API
  • Fetch
  • local storage
  • console

gif2.1.gif

We can use all the Web APIs through the window keyword.

Callback Queue / Task Queue:-

A Callback queue is a Queue of tasks that are executed after the current task.

1_lnd5I-p8U7TCqJ4SJB1B4A.gif

After the timer gets expired, the callback function is put inside the callback queue, and the Event loop checks if the call stack is empty and then pushes the callback function to the call stack from the callback queue. and the callback function is removed from the callback queue.

MicrotTask Queue :-

MicrotTask queue has more priority as compared to the callback queue.

All the callback functions which come through the promise or async operations will go inside the microtask queue.

1__0CnS0bHNX7HMBLri3gNng.gif