JavaScript Event Loop

Minhazul Hasan Sohan
2 min readNov 4, 2020

--

What is JavaScript Event Loop??? — Well before describing this let’s just have a look at the piece of code.

eventLoop.html
output

Here clearly shows that our JavaScript skipped the second function and execute the third function first…so, What’s the catch???

Here the idea of event loop comes from. JavaScript is a single-threaded, non-blocking, asynchronous, concurrent language.

Thread is like an event in other word it’s simply a sequence of code execution which can be executed independently of one another. JavaScript is a single-threaded programming language which means it has a single call stack and a single memory heap & it can do one thing at a time.

Asynchronous

JavaScript is single-threaded but it can behave as if it were multi-threaded. It can put on hold, that is put on the Callback Queue, all asynchronous code until it is processed…. an API call, callbacks, I/O events, and can continue the current executions. This is possible because the JavaScript engines under the hood use real multi-threading languages. For example C++ for Chrome or Rust for Firefox. They provide the Web API under the browser hood.

In our code :

  • Firstly, the irstFunction() is pushed to the call stack and then it immediately executed in our console.
  • Secondly, the browser API has a setTimeout method we call it from the browser API. It goes to the call stack and its asynchronous callback secondFunction() goes to the WebAPI’s queue, where it waits for the call, which we want to happen after 5 seconds(5000). In the meantime, the program continues the code and we see thirdFunction() in the console.
  • After 5 second the WebAPI transform our secondFunction() into callback queue then it pushed into our stack and executed.

The event loop, which is a vital part of the javascript engine, lets the runtime know that the call stack is empty and the event in the callback queue is requested. This process constantly checks if the call stack is empty and, monitors whether there is an event in the callback queue waiting to be invoked.

--

--

Minhazul Hasan Sohan

চিত্ত যেথা ভয়শুন্য, উচ্চ যেথা শির