JavaScript — Event Loop
JavaScript is a single-threaded, it’s job is to go through all the lines of the code in an application and process them one at a time, the main issue on this is that if in the code being running, a line happens to take a long time to return, all the code after that line will be blocked.
So how does JavaScript engine know how to process a single line of code at a time? It uses a call stack.
A call stack is a mechanism in a web browser to keep track of its place in a script that calls multiple functions, like for example what function is currently being run, what functions are called from within that function and which function should be called next.
Now that we get how the call stack works in the JavaScript engine, let’s get back to the idea of blocking code, and how to avoid it, here is when the asynchronous callback function arises. An asynchronous callback function is just like any other function we’re used to writing in JavaScript, but this function doesn’t get executed till later. For example setTimeout() function.
Right after the setTimeout function is executed, something special happens here the browser places setTimeout’s callback function into an Event Table (is like a registration booth): the call stack tells the event table to register a particular function to be executed only when a specific event happens. And when the event does happen, the event table will simply move the function over to the Event Queue. The event queue its simply a staging area for functions waiting to be invoked and moved over to the call stack. The JavaScript engine follows a very simple rule: there’s a process that constantly checks whether the call stack is empty, and whenever it’s empty, it checks if the event queue has any functions waiting to be invoked. If it does, then the first function in the queue gets invoked and moved over into the call stack. If the event queue is empty, then this monitoring process just keeps on running indefinitely.
And voila , this Event I just described is the Event Loop!