July 10, 2020

How javasript event Loop works?

In today’s world Javascript is the one of the most dominating scripting language and people are crazy about it and they want to develop number of things with it but Before that you should understand how javascript works exactly , Therotically we all know javascript is single threaded but on the other side its non-blocking I/O also, Have you ever imagined even though its single threaded , It’s very fast because event looping concept in javascript.

Event loop is a process which is created every time where any application instatiate like per browser tab or node js application

Let’s learn it in detail

High level Event loop design

Javasript Event Loop

In above diagram you able to see some section let’s discuss it one by one

Please subscribe for web development tutorials

Heap Memory

Heap is the place (memory) where objects are stored when we define variables.

Call stack

Call stack is a place where all synchronous code like functions, variable push one by one and it executes in LIFO(Last in first out) manner .Event loop consistently check call stack to confirm that is it empty or not because call stack has high priority upon execution. Event loop not allow message to execute before call stack get empty, So always make sure that you should not write complex code that takes time to execute like infinite for loop which blocks total runtime execution

Lets take an example so that we understand how

const foo = () =>{console.log('In foo')};
const bar = () => { console.log('Inside bar')};
const baz = () => { 
    bar();
    foo();
 };
baz();

In above example, when interpreter scans code it declares function foo , bar, baz and alloted a memory to it in heap, Then it found function call for baz(). baz() function pushed into the call stack inside there are two more calls bar() and foo() which executes first then baz() finishes its execution

Message Queue

Message queue comes into the picture when asynchronous code comes into action like setTimeout, ajax calls, dom events etc.

Let’s take an example

console.log('sync 1');
setTimeout(function(){
console.log('async 2')
},10000);
console.log('sync 3')

As we can see in above example, Everyone thinks that as per single threaded nature of javascript it will first print ‘sync 1’ then after 10 seconds it will print ‘async 2’ and then ‘sync 3’.

But you are wrong javascript will not work like this it will print like below

sync 1
sync 3
async 2

Let’s see how its possible, In javascript , When interpreter scans code one by one wherever it find’s synchronous code it will be added into the call stack and whenever it detects asynchornous code like dom events, setTimeout or ajax calls it added into the message queue it will seperately executed into the message queue so that means javascript engine never waits for async code to execute it will executed seperately and when code in call stack executed totally and call stack is empty then code from message queue runs.

call stack has high priority than message queue it means if we have setTimeout with 10 seconds, It’s not necessory it will execute after 10 seconds, It will execute after call stack is empty. So make sure you should not add code that blocks the execution like infinite loop.

JOB QUEUE

we have not included job queue into event loop design but its new thing which was introduced in ES6. It mostly used by promises where it executes as soon as call stack get empty. It means if we setTimeout with 0 timer and then after that we have promise so promise will run first before setTimeout

let’s take an example

const foo = () =>{console.log('Inside foo')};
const bar = () => { console.log('Inside bar')};
const baz = () => { 
   setTimeout(bar,0);
    new Promise((resolve,reject)=>{
      resolve('Execute before bar which is inside bar')
    }
    ).then(res=>resolve(res));
    foo();
 };
baz();

Above code will return output as

Inside foo
Execute before bar which is inside bar
Inside bar

So as per above example promis executed first because of job queue concept which has higher priority than Message queue.

Thanks for reading,If you like post please comment down and subscribe to newsletter for more updates like this.

Leave a Reply

Your email address will not be published. Required fields are marked *