# 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 for 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 ` ``` ...But we also may want to show something during the task, e.g. a progress bar. If we split the heavy task into pieces using `setTimeout`, then changes are painted out in-between them. This looks prettier: ```html run
``` Now the `
` shows increasing values of `i`, a kind of a progress bar. ## Use case 3: doing something after the event In an event handler we may decide to postpone some actions until the event bubbled up and was handled on all levels. We can do that by wrapping the code in zero delay `setTimeout`. In the chapter we saw an example: custom event `menu-open` is dispatched in `setTimeout`, so that it happens after the "click" event is fully handled. ```js menu.onclick = function() { // ... // create a custom event with the clicked menu item data let customEvent = new CustomEvent("menu-open", { bubbles: true }); // dispatch the custom event asynchronously setTimeout(() => menu.dispatchEvent(customEvent)); }; ``` ## Macrotasks and Microtasks Along with *macrotasks*, described in this chapter, there are *microtasks*, mentioned in the chapter . Microtasks come solely from our code. They are usually created by promises: an execution of `.then/catch/finally` handler becomes a microtask. Microtasks are used "under the cover" of `await` as well, as it's another form of promise handling. There's also a special function `queueMicrotask(func)` that queues `func` for execution in the microtask queue. **Immediately after every *macrotask*, the engine executes all tasks from *microtask* queue, prior to running any other macrotasks or rendering or anything else.** For instance, take a look: ```js run setTimeout(() => alert("timeout")); Promise.resolve() .then(() => alert("promise")); alert("code"); ``` What's going to be the order here? 1. `code` shows first, because it's a regular synchronous call. 2. `promise` shows second, because `.then` passes through the microtask queue, and runs after the current code. 3. `timeout` shows last, because it's a macrotask. The richer event loop picture looks like this (order is from top to bottom, that is: the script first, then microtasks, rendering and so on): ![](eventLoop-full.svg) All microtasks are completed before any other event handling or rendering or any other macrotask takes place. That's important, as it guarantees that the application environment is basically the same (no mouse coordinate changes, no new network data, etc) between microtasks. If we'd like to execute a function asynchronously (after the current code), but before changes are rendered or new events handled, we can schedule it with `queueMicrotask`. Here's an example with "counting progress bar", similar to the one shown previously, but `queueMicrotask` is used instead of `setTimeout`. You can see that it renders at the very end. Just like the synchronous code: ```html run
``` ## Summary A more detailed event loop algorithm (though still simplified compared to the [specification](https://html.spec.whatwg.org/multipage/webappapis.html#event-loop-processing-model)): 1. Dequeue and run the oldest task from the *macrotask* queue (e.g. "script"). 2. Execute all *microtasks*: - While the microtask queue is not empty: - Dequeue and run the oldest microtask. 3. Render changes if any. 4. If the macrotask queue is empty, wait till a macrotask appears. 5. Go to step 1. To schedule a new *macrotask*: - Use zero delayed `setTimeout(f)`. That may be used to split a big calculation-heavy task into pieces, for the browser to be able to react to user events and show progress between them. Also, used in event handlers to schedule an action after the event is fully handled (bubbling done). To schedule a new *microtask* - Use `queueMicrotask(f)`. - Also promise handlers go through the microtask queue. There's no UI or network event handling between microtasks: they run immediately one after another. So one may want to `queueMicrotask` to execute a function asynchronously, but within the environment state. ```smart header="Web Workers" For long heavy calculations that shouldn't block the event loop, we can use [Web Workers](https://html.spec.whatwg.org/multipage/workers.html). That's a way to run code in another, parallel thread. Web Workers can exchange messages with the main process, but they have their own variables, and their own event loop. Web Workers do not have access to DOM, so they are useful, mainly, for calculations, to use multiple CPU cores simultaneously. ```