JavaScript Event Loop (Part 1): Microtasks, Macrotasks, and Ordering
JavaScript is single-threaded. The event loop is what runs your code, handles I/O callbacks, and decides when to paint. Understanding microtasks vs macrotasks (tasks) is critical for debugging async code and for writing predictable batching and scheduling. This post explains the model and how to use it as a senior engineer.
Single-threaded and the loop
The JavaScript engine runs one task at a time. When a task runs, it runs to completion (no preemption in the middle of synchronous code). When the task finishes, the engine can run microtasks (e.g. Promise callbacks, queueMicrotask). After draining the microtask queue, it may render (in the browser), then pick the next task from the task queue. So the high-level order is: