The Talk That Made Me Finally Understand How the Event Loop Works
When I first heard about the event loop, the concept kind of made sense.
I knew that Node.js is single-threaded but also very fast at the same time. It's using the event loop to handle thousands of concurrent requests. How exactly it accomplished that though, was a mystery to me.
I also knew not to block the event loop in Node.js otherwise server performance would suffer.
Everyone warned against blocking the event loop!
I was able to write asynchronous code that worked. I could also modify async code written by others without introducing new bugs (most of the time). But honestly, there were many moments where I had no idea why my code worked. 🤷🏼♂️
Understanding the event loop
The event loop was an abstract concept and I did not know what was happening behind the scenes. That is until I watched Philip's talk at JSConf EU. This fantastic talk finally made the concept click in my head.
I'm a visual learner and Philip's animated explanation of how the event loop works helped me truly understand what was happening behind the scenes.
From that point on, I never looked at async code the same way again. It was a stepping stone to writing more complex asynchronous code patterns. I could confidently refactor callbacks to promises and async/await.
The number of times I reached out to Google for help reduced significantly. I didn't need Stack Overflow to hold my hand anymore and I could fix bugs all by myself.
Keep reading for my takeaways of Philip's talk, or skip to the end if you want to watch it right away.
Philip then proceeds with an animated explanation of how the call stack works and what happens when we introduce blocking code in our programs. This wasn't something I hadn't known before, but it's an important refresher because next, we'll get to see how the event loop comes into play.
When you call an asynchronous function, the function runs in a separate thread until it completes. After completion, the callback function is pushed onto the callback queue. It's then the job of the event loop to grab the callback from the callback queue and push it to the stack when it's empty — which effectively runs the callback.
When most people talk about blocking the event loop, what they mean is having code that runs for a relatively long time and therefore occupying the call stack. When the call stack is busy, the event loop doesn't get the chance to clear the callback queue.