Javascript Event loop: What and How it works?

Kamruzzaman Kamran
3 min readNov 3, 2020
Event loop

Before going on to the Event loop, let’s take an overview of how JavaScript works.

We all have heard of the V8 Engine as a concept already, and also understand that JavaScript is single-threaded or that a callback queue is often used. This means that it does have one call stack and one memory stack. It executes the code in order and must finish the execution of the piece code before moving to the next one.

The call stack is responsible for maintaining track of all line operations to be executed. Whenever a function ends, it’s popped out of the stack.

The relationship of JavaScript with HTML is done by Events that occur when a user or browser manipulates a page. When the page loads, it’s called an Event. When the user clicks a button, that click is an Event. Other examples include Events such as pressing a key, closing a window, changing a window, etc.

The event loop is the mystery behind the asynchronous programming of JavaScript.The JavaScript runtimes contain a message queue that holds a list of messages to be processed and their related callback functions. These messages are queued in response to external events where a callback function has been given. In a loop, the queue is scanned for the next message, and when a message is detected, the callback for that message is executed.

The execution will depend on the number of waiting tasks in the queue. In the example below, the message “this is just a message” will be written to the console before the callback message is processed. Since the wait is the minimum time needed for the running time to process the request.

( function() {

console.log(‘this is the start’);

setTimeout(function callBack1() {
console.log(‘Callback 1: this is a msg from call back’);
});
// has a default time value of 0

console.log(‘this is just a message’);

setTimeout(function callBack2() {
console.log(‘Callback 2: this is a msg from call back’);
}, 0)
;

console.log(‘this is the end’);

})();

// “this is the start”
// “this is just a message”
// “this is the end”
// “Callback 1: this is a msg from call back”
// “Callback 2: this is a msg from call back”

Basically, setTimeout has to wait for all the queued messages code to be completed even if you set a time limit for your setTimeout.

A very fascinating aspect of the event loop paradigm is that, unlike most other languages, JavaScript never blocks. That is why it’s called Non-Blocking. The I / O handling is usually done through events and callbacks, even while an application is waiting for a DataBase query to be returned or an XHR request to be returned, other items like user feedback may still be processed.

There is an interesting yet much effective YouTube Video on the Event loop that will help you understand the term much easier.

--

--