JavaScript Event Loop Explained

Anoop Raveendran
Dec 27, 2017 · 4 min read

“How is JavaScript asynchronous and single-threaded ?” The short answer is that JavaScript language is single-threaded and the asynchronous behaviour is not part of the JavaScript language itself, rather they are built on top of the core JavaScript language in the browser (or the programming environment) and accessed through the browser APIs.

Now for the long answer, let me try through 2 sample code snippets.

Basic Architecture

Overview of major components in a browser

Code Snippet 1 : Intrigue the mind

Here we have the main function which has 2 console.log commands logging ‘A’ and ‘C’ to the console. Sandwiched between them is a setTimeout call which logs ‘B’ to the console with 0ms wait time.

Inner working during the execution

So the delay parameter in setTimeout(function, delayTime) does not stand for the precise time delay after which the function is executed. It stands for the minimum wait time after which at some point in time the function will be executed.

Code Snippet 2 : Deeper Understanding

This article is heavily influenced by Philip Roberts’s talk on JS Event Loop. For a live demonstration of working of the event loop, head on to http://latentflip.com/loupe/ created by him. Thank you Philip for the video, it helped me understand JavaScript much better.

Frontend Weekly

It's really hard to keep up with all the front-end…

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

Anoop Raveendran

Written by

JavaScript Dev with an affinity to React. https://anooprav7.com/

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co