What is JavaScript Event Loop?

What is JavaScript Event Loop?

JavaScript Event Loop is one of the most important characteristics through which you can understand the basic work process of JavaScript. It is due to the Event loop through which asynchronous operations are possible.

But you may ask as Javascript is a single-threaded language, then how it can perform asynchronous functions? It is due to the fact that Javascript asynchronous behavior is not part of its own language but is built on top of the JavaScript in the browser and can be accessed through browser APIs. Lets us move forward and understand how JavaScript is a single-threaded language can perform all these asynchronous functions.

Limitation of Single-Threaded Languages

JavaScript being single-threaded means that it can’t execute two pieces of code in parallel. For example, Imagine you wrote code for a UI. While the Call stack is busy executing functions, but in meantime, your browser can’t do anything else – It is blocked.

This means browsers can’t do anything while your code is being executed, which directly affects the UI of your app and performance. But let’s just say, your browser is also executing different many files then after some time, it will become unresponsive and you can’t scroll or click around.

Also read, JavaScript Functions | How does Function works in Js {Detail Explanation}

Concurrency model in JavaScript

JavaScript concurrency model is built of event loop operation, which is actually responsible for the order of the execution of the code. So to understand the structure and working of Event Loop, first, we need to know some of its component which collectively works together to form Event loop in browsers.

Call Stack

As we all know Call Stack, is the one who is responsible to keep track of all the operations and functions to be executed in a given piece of code. And whenever the function gets executed, it pops up from the stack. It follows the LIFO (Last in First Out) sequence order.

Let’s see an example,

const funct1 = () => {
	console.log('function 1')
}

const funct2 = () => {
	console.log('function 2')
}

const funct3 = () => {
	console.log('function 3')
}


funct3()
funct2()
funct1()

and when we run this code, we get,

function 3
function 2
function 1

In call stack first, funct3 is executed followed by funct2 and funct1.

Heap

Heap is a large unstructured, memory region where all objects are allocated and is place to store and write information.

Also read, Why You Can Benefit From Learning To Code

Queue

The queue is responsible for sending different functions to track for processing. It follows FIFO (First in First Out) sequence order, in which all the functions are sent for executions. It is where callbacks are en-queued, executed, and de-queued. This type of queue is also known as ‘Task Queue‘.

There is also ‘Job Queue‘, which was introduced in the ES6 update. It mostly deals with any asynchronous behavior of Promises. To understand the difference between Task Queue and Job Queue is not all task has equal priority, they are divided into macrotask and microtask. Examples of macrostask are, setTimeout, setInterval, setImmediate, I/O tasks, or UI rendering, and for microtask are, Promises.

Web APIs

Web APIs or Browser APIs, which are built inside the browsers, help in performing various useful complex operations and to help to access or modify data. They are not part of JavaScript Language but are built on top of the core JavaScript. For example, Geolocation API, local Storage, DOM APIs, and even console.

You will be surprised to know that setTimeout() or fetch(), is not the part of JavaScript language but are web APIs.

event loop javascript

So What is the Event Loop?

Event Loop in simple words has only one job, which is to track the call stack and Task queue (Callback queue). It checks if the call stack is empty then takes the first event from the callback queue and then pushes it in the call stack, maintaining the sequence.

Let us understand it with one example,

console.log('Start of Loop');
setTimeout(function timer() { 
    console.log('Timer');
}, 6000);
console.log('End of Loop');

We would execute the above code and then observe what is happening, for visualization we would use, latentflip.com/loupe. So when we run over the above code, this is happening behind the scene in the browser,

event loop example
  1. Before running the code, we see, browser’s console and the call stack are empty.
  2. console.log(‘ Start of Loop ‘), is added to the call stack.
  3. console.log(‘ Start of Loop ‘), is executed.
  4. console.log(‘ Start of Loop ‘), is removed from the call stack.
  5. setTimeout(function timer() { … }), is added to the call stack.
  6. setTimeout(function timer() { … }), is executed. It will be handled outside the call stack as it is the browser’s API, And once the time, which is 6000ms is over then it will be en-queued in the callback queue.
  7. setTimeout(function timer() { … }), is completed and removed from the call stack.
  8. console.log(‘ End of Loop ‘), is added to the call stack.
  9. console.log(‘ End of Loop ‘), is executed.
  10. console.log(‘ End of Loop ‘), is removed from the call stack.
  11. After 6000ms, once the timer is completed, it en-queued the callback function timer into the callback queue.
  12. The event loop takes the callback function timer and pushes it into the call stack.
  13. The callback function timer is executed and console.log(‘ Timer ‘), is added to the call stack.
  14. console.log(‘ Timer ‘), is executed.
  15. console.log(‘ Timer ‘), is removed from the call stack.
  16. The callback function timer is removed from the call stack.

And we will get this as a output in browser’s console,

Start of Loop
End of Loop
Timer

Note – The delay parameter which we pass in the setTimeout(function(), delayTime), does not mean that after this exact time the callback function passes in it will be executed, instead, It actually means, the minimum wait time after which in some point function will be executed.

Also read, An Easy Explanation of JavaScript Closure

Final Words

I hope you able to understand the working of Event loop, It is all about managing things in organized manner. Initially it might all sound little confusing but as you keep practicing, you will able to get hold on it.

If you like my article please share more with your friends and colleagues, and please bookmark this website to get awesome articles like these more.

Table of Contents