What is the JavaScript event loop?

Avatar of Neil Gebhard Neil Gebhard
/

The JavaScript event loop helps determine what parts of your code runs and when.

It is needed because JavaScript is single-threaded. At any particular time, only one sequence of code can be executing. There is no concurrency. Yet, what happens when two things need to execute at the same time?

First, we need to know that JavaScript has run-to-completion semantics. This means that the current task is run to completion before the next task is executed.

When a JavaScript program starts, it runs from top to bottom without interruption. After, the program may exit. However, if there are event listeners, the program "waits".

When an event is fired, the event listener calls its event handler to run its block of code. If there’s no other event waiting to be fired, the code executes immediately. Otherwise, it joins the queue and waits until the JavaScript runtime is freed up.

If another event is fired in the meantime, the event handler joins the queue once again and waits for its turn to execute.

This happens over and over again as needed in a loop.

It's worth noting that this is a simplistic model of the JavaScript event loop. I'm skipping the use of some jargon, but the core idea of the JavaScript event loop is there. Having an understanding of the underlying mechanism of the way the JavaScript executes code will help you write better code.