Javascript Event Loop — Is it a Bermuda triangle?

Ramanathan Chockalingam
2 min readMar 16, 2021

--

It is a puzzle time, Try out the below code in your browser console and let’s see which one gets printed on the console first,

Does setTimeout print the message in the console after a second?

If your answer is Yes, Sorry I couldn’t see the message in the console.

If your answer is No, Is it really a Bermuda triangle that swallowed our timeout code?

What really a Javascript event loop is?

Javascript event loop is queue which helps to manage the asynchronous tasks.

An event loop contains an internal event queue that stores the events happening in the browser application and it will be processed later one by one in the javascript execution environment.

Hope you aware that javascript is a single-threaded language that handles all the functionalities in the browser like rendering pages, script execution, event handling, and etc., with a single thread.

If the thread is getting blocked by any of the code execution, it will be blocked and not allowed to move further until the execution completes.

If the thread is free and there is no more code for execution then the call stack will be empty so the event loop pushes the event handlers of occurred events to the call stack. The pushed functions on the call stack will be processed by the execution thread.

Microtasks Queue

In addition to the event queue, there is one more queue called the micro-tasks queue that queues promise. The event loop will check always the micro-tasks queue first and completely drains out the queue if any items queued, before proceeding to process the events queued in the event queue.

let’s review our code once to know what actually happened,

On executing the above script setTimeout function will be put into the event loop queue and further execution continues since the while loop is infinite, the execution thread will not be freed and the call stack is always occupied. So there is no chance for the event loop to push the timeout code into the call stack. so that the timeout message is not getting printed on the console even after a second.

Why it is important to aware of JS event loop?

Doing heavy computational tasks in the execution thread leads to the page becomes unresponsive for further actions. It is better to outsource such tasks to web workers. Web workers will have their own execution environment which includes an event loop too.

As part of the best practices, It is mentioned to place your scripts at the bottom of the body tag. Why because if the thread hits the script, it starts processing the JS code and stops rendering the page till it completes the code execution. Users may see partially rendered or no page till its code execution.

Thanks for reading!!

--

--

Ramanathan Chockalingam
Ramanathan Chockalingam

No responses yet