Logo

TODAY I LEARNED

Javascript event loop

The event loop is the secret behind JavaScript's asynchronous programming. JS executes all operations on a single thread, but using a few smart data structures, it gives us the illusion of multi-threading but first we have to understand the Call Stack.

Call Stack

The call stack works based on the LIFO principle(last in first out) When you execute a script, the JavaScript engine creates a Global Execution Context and pushes it on top of the call stack.

function multiply(a, b) {
    return a * b
}

function squere(n) {
    return multiply(n, n)
}

function printSquere(n) {
    var result = squere(n)
    console.log(result)
}

printSquere(4)

**Stack**
4- multiply
3- squere
2- printSquere
1- main

Result: 16

Call Stack with async callbacks (Even loop)

The event loop facilitates this process; it constantly checks whether or not the call stack is empty. If it is empty, new functions are added from the event queue. If it is not, then the current function call is processed.

An example of this is the setTimeout method. When a setTimeout operation is processed in the stack, it is sent to the corresponding API which waits till the specified time to send this operation back in for processing.

console.log('hi')

setTimeout(()=> {
  console.log('there')
},5000)

console.log('bye')

**Stack**
3- there
2- bye
1- hi

**webapis**
setTimeout callback(cb)

**taskqueue**
callback(cb)

**evenloop**
move cb to stack

In the example the setTimeout Callback enters the webapi stack executes and then goes to the task queue and waits for the stack to become empty and the event loop moves the callback to the stack.

Learned by leyaim-jimenez on Oct 1, 2021

973983 adforcodereview v3 0211021 c02 021121