The Javascript Event Loop

As part of our introduction to Javascript in The Iron Yard’s Ruby on Rails course, we watched this talk by Philip Roberts, titled “What the heck is the event loop anyway?” As someone who is just about to get into how to use Javascript outside of basic tutorials, this talk was my first real introduction into how Javascript actually interacts with the browser and I must say, it was fascinating. Obviously, I didn’t understand some of the stuff Mr. Roberts said, but I understood a lot more than I thought I would.

The way I understand the event loop is basically like maximizing the processing power of a single-core CPU. As a disclaimer, I don’t know ANYTHING technical about how CPUs actually work, but I generally understand that a multi-core CPU can process multiple things at the exact same time while a single-core CPU can process only one. (As an aside, if anyone who reads this and understands how CPUs work would like to explain them to me, I’d love to learn.)

To clarify what I mean, I will explain this in the sense that one person = one CPU. If you give this one person a huge stack of papers to fill out, it will take a long time. It would be better if you could have two people working at the same time, right? Right. To me, the Javascript event loop isn’t like a second processor, but it’s more like the first processor has a really good assistant. This assistant, based on what each piece of paper in the stack requires the CPU to do, will prioritize the order in which the CPU signs the papers. Mr. Roberts said that Javascript developers will frequently say “don’t block the stack,” and to bring this into my ever-worsening analogy, this basically means that you shouldn’t fill the top of the stack of papers with paperwork that takes a long amount of time, but rather, you should sign ten easy papers for every one tedious piece of paperwork. The event loop, or the great assistant, will sort the paperwork to do just that as long as the pieces of paper are appropriately labeled.

This analogy is getting out of hand, but generally speaking, I think I mostly understand what Mr. Roberts was talking about. One thing that interested me is that he very briefly mentioned that Ruby, unlike Javascript, is a multithreaded language, yet I thought Ruby was a single-threaded language. That goes to show how much I have to learn, and I love watching these videos that really key me into the deep layers of programming. I can’t wait to learn more.