The JavaScript Event Loop

The JavaScript Event Loop
The event loop visualized

The event loop is a way for the browser to deal with asynchronous events. Even if you are unfamiliar with the event loop, you have likely had encounters with the event loop unbeknownst to you. An infinite recursive call will crash the program by overloading the stack. You may also have had peculiar experiences with setTimeout(cb, 0) magically working. By itself, the Javascript V8 Engine does not provide APIs for callback-related events. These include event listeners, AJAX requests, or setTimeout. By default, JavaScript is single-threaded, which means it only has one call stack. We don’t want slow code to block the call stack, or else the user will not be able to interact with the page in a fluid, responsive way. 

For asynchronous processes, the async code is pushed onto the call stack. In the case of a setTimeout, the browser will utilize the setTimeout Web API, and create a timer for the completion of the setTimeout call. The callback inside of setTimeout will be pushed onto the task queue/callback queue. After the rest of the synchronous events have been popped off of the call stack(the call stack is empty), the event loop will push the callback inside of setTimeout to the call stack, which JavaScript finally runs. For cases where setTimeout(cb, 0) is used, the setTimeout only runs after the call stack is empty, which means it runs right after all of the synchronous code.

In the rendering process, the browser pushes the function for rendering onto the task queue on each 16.6 millisecond interval to ensure a fluid, 60 frames per second user experience. If the call stack has slow, synchronous code, the browser will not be able to push that render callback in the task queue onto the main stack, which leads to horrible user experiences. The render callback is given higher priority than the other async callbacks inside of the queue. The event loop is an important concept for JavaScript developers to understand to become better engineers.

 

Video that helped me understand the event loop: https://www.youtube.com/watch?v=8aGhZQkoFbQ

Updated:


Comments