Back to Home

Event loop: microtasks and macrotasks

Browser JavaScript execution flow, as well as in Node.js, is based on an event loop. Understanding how event loop works is important for optimizations, and sometimes for the right architecture. In this chapter we first cover theoretical details about how things work, and then see practical applications of that knowledge.

Event Loop

The event loop concept is very simple. There’s an endless loop, where the JavaScript engine waits for tasks, executes them and then sleeps, waiting for more tasks. The general algorithm of the engine: 1. While there are tasks: - execute them, starting with the oldest task. 2. Sleep until a task appears, then go to 1. That’s a formalization of what we see when browsing a page. The JavaScript engine does nothing most of the time, it only runs if a script/handler/event activates. Examples of tasks: - When an external script