Related Articles

Related Articles

What is an event loop in JavaScript ?
  • Last Updated : 09 Dec, 2020

JavaScript is a single-threaded asynchronous programming language. But what does it actually mean? What is this event loop in JavaScript that we all keep talking about? 

What does it actually mean when we say JavaScript is single threaded?

It means that the main thread where JavaScript code is run, runs in one line at a time manner and there is no possibility of running code in parallel.

Example:



Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

console.log("Before delay");
  
function delayBySeconds(sec) {
   let start = now = Date.now()
   while(now-start < (sec*1000)) {
     now = Date.now();
   }
}
  
delayBySeconds(5);
  
// Executes after delay of 5 seconds
console.log("After delay");

chevron_right


Output:

Before delay
(... waits for 5 seconds)
After delay

Memory allocation in JavaScript:

1) Heap memory: Data stored randomly and memory allocated.

2) Stack memory: Memory allocated in the form of stacks. Mainly used for functions.

Function call stack: The function stack is a function which keeps track of all other functions executed in run time. Ever seen a stack trace being printed when you ran into an error in JavaScript. That is nothing but a snapshot of the function stack at that point when the error occurred.



Example:

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

function LevelTwo() {
   console.log("Inside Level Two!")
}
  
function LevelOne() {
   LevelTwo()
}
  
function main() {
   LevelOne()
}
  
main()

chevron_right


Order at which functions get executed i.e get popped out of the stack after a function’s purpose gets over as shown below:

Event loop: An event loop is something that pulls stuff out of the queue and places it onto the function execution stack whenever the function stack becomes empty.

The event loop is the secret by which JavaScript gives us an illusion of being multithreaded even though it is single-threaded. The below illusion demonstrates the functioning of event loop well:

Here the callback function in the event queue has not yet run and is waiting for its time into the stack when the SetTimeOut() is being executed and the Web API is making the mentioned wait. When the function stack becomes empty, the function gets loaded onto the stack as shown below:

That is where the event loop comes into picture, it takes the first event from the Event Queue and places it onto the stack i.e in this case the callback function. From here, this function executes calling other functions inside it, if any.

This cycle is called the event loop and this how JavaScript manages its events.

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :