Better Programming

Advice for programmers.

Follow publication

Member-only story

Understanding the Node.js Event Loop

Tyler Hawkins
Better Programming
Published in
8 min readMay 18, 2021

--

Man standing in front of lights
Photo by Jacqueline Day on Unsplash.

JavaScript is single-threaded, so how does it handle asynchronous code without blocking the main thread while it waits for an action to complete? The key to understanding the asynchronous nature of JavaScript is understanding the event loop.

In the browser, the event loop coordinates the execution of code between the call stack, web APIs, and the callback queue. Node.js, however, implements its own “Node.js event loop” that is different from the regular “JavaScript event loop.” How confusing!

The Node.js event loop follows many of the same patterns as the JavaScript event loop but works slightly differently, as it doesn’t interact with the DOM but does deal with things like input and output (I/O).

In this article, we’ll dive into the theory behind the Node.js event loop and then look at a few examples using setTimeout, setImmediate, and process.nextTick. We'll even deploy some working code to Heroku (an easy way to quickly deploy apps) to see it all in action.

The Node.js Event Loop

The Node.js event loop coordinates the execution of operations from timers, callbacks, and I/O events. This is how Node.js handles asynchronous behavior while still being single-threaded…

--

--

Tyler Hawkins
Tyler Hawkins

Written by Tyler Hawkins

Staff software engineer. Continuous learner. Educator. http://tylerhawkins.info

Write a response