JavaScript Event Loop – how does it work?

If you – like me – have ever wondered how JavaScript is able to handle callbacks and do stuff asynchronously, wonder no more, but take a look at this brilliant video by Philip Roberts:

I really recommend watching the whole video. But if you don’t have the time for that, I try to give you a summary of the most important points:

JavaScript is:

  • single-threaded
  • non-blocking
  • asynchronous
  • concurrent

JavaScript has:

  • call stack
  • event loop
  • callback queue
  • access to Web APIs offered by the browser

JavaScript is run by a JavaScript Engine. Each browser has its own implementation of it. Chrome i.e. uses its V8 JS Engine, Firefox is using SpiderMonkey and Microsoft Edge uses an Engine called Chakra.

Each of these engines is implemented on its own and has its own pros and cons.

Async with JavaScript

Although JavaScript always gets executed in just one single thread, it is possible to call methods asynchronously (non-blocking). This is actually crucial for time demanding functions, as they would otherwise block the execution of all the other code.

So how does that work if JavaScript is always running single-threaded you may ask? Actually this is possible by using Web APIs that are implemented in the browser, which handle the whole concurrency stuff. So you do have concurrency in the way JavaScript is executed, but you cannot directly control it, only by using the Web APIs of the browser.

This is explained very nicely at around 12:02 in the video.

Philip Roberts even wrote a web tool to simulate how JavaScript code is being run. It is called Loupe and it does a pretty good job at visualizing everything that happens behind the scenes. No worries, he even explains how to use the tool in the video.

You can also check out the presentation by Thomas Hunter if you want to get more information on this topic.

I have to say, this video opened my eyes. And I have a much better understanding now of what goes on under the surface of my browser.