The Event Loop

JavaScript is single-threaded. Which avoid a lot of complexity and pitfall of multi-threading programming.

The event loop allows JavaScript to handle multiple IO operations asynchronously without blocking the main execution thread.

The only caveat of this approch is that you should never block the main thread. No compute extensive work or blocking IO calls. Instead, offload heavy computations to other threads (workers).

Basic Flow of the Event Loop

Synchronous code executes first, and is placed on the call stack.

Asynchronous tasks (e.g., setTimeout, I/O operations) are handed off to the browser's background processes or to libraries like libuv (Node.js) or tokio (Deno).

Once the asynchronous task is complete, its callback function is placed in the callback queue.

The event loop checks if the call stack is empty. If it is, it will pull the next task from the callback queue and place it on the call stack for execution.