Javascript Event Loop and Concurrency

Javascript Event Loop and Concurrency

Understanding Event Loop

Call Stack

function thirdFn() {    console.log('Called from thirdFn()');}function secondFn() {    thirdFn();    console.log('Called from secondFn()');}function firstFn() {    secondFn();    console.log('Called from firstFn()');}firstFn();// Called from thirdFn()// Called from secondFn()// Called from firstFn()

A Single-Threaded World

function secondFn() {    console.log('Called from secondFn()');}function firstFn() {    console.log('Called from firstFn()');    for (var i=0; i<1000000000; i++) {        console.log(i);    }    secondFn();}firstFn();// Called from firstFn()// 1// 2// 3// .// .// .// 1000000000// Called from secondFn()

Enter The Concurrency

Callback Queue

(function() {    console.log('1st');    console.log('2nd');    setTimeout(function() {        console.log('3rd');    }, 0);    setTimeout(function() {        console.log('4rd');    }, 0);    console.log('5th');})();// 1st// 2nd// 5th// 3rd// 4th




Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store