Skip to Content

The Event Loop

Sharing is caring!

I’m going to level with you, no matter what I write in this post, it will not be as illuminating as this video on YouTube.

However, for the purpose of providing a point of reference in other posts, and in he event that watching a video isn’t your thing, I’ll attempt to summarize.

The asynchronous nature of many JavaScript operations often confuses folks who are new the language, I’m including myself in that group, particularly if you’re coming from something like PHP.

For the purposes of this post I’m going to confine the context to the browser.

JavaScript is single threaded language, one thing happens at a time, though the event loop can make this confusing.

Every thread in JavaScript has its own event loop, in most cases, particularly in the browser most processing is taking place in the main thread. Your code will start to execute in the first loop. So as the page cycles through function calls and DOM look ups, JavaScript will take action, adding DOM classes, introducing new element, adding event listeners or whatever else you’ve asked JavaScript to do.

Many of these operations and sub operations will be synchronous, some examples:

  • DOM interactions, including: Selecting elements, adding elements, adding event listeners
  • Reading Cookie state
  • Time operations

These feel very straightforward and variable assignment against these operations is clear.

const button = document.querySelector('#my-button')

The place where things start to break down is in Asynchronous (async) operations. These operations are what make understanding the event loop worth the effort. Async operations require more than one turn of the event loop. Some Examples:

  • xmlhttp or fetch requests
  • setTimeout
  • localStorage

Sometimes these operations might take more than one turn of the event loop depending on any number of factors, response times for requests, or perhaps the amount of time applied to setTimeout. A common tactic for delaying operations often used a setTimeout with a zero value to force an operation to happen at the end of the first event loop.

The principle of the event is the reason for Callbacks, Promises and Async/Await.

Previous
Web Workers in WordPress: Part 1
shares