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. 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. Tasks are set – the engine handles them – then waits for more tasks (while sleeping and consuming close to zero CPU). Tasks from the queue are processed on “first come – first served” basis. Rendering never happens while the engine executes a task. Changes to the DOM are painted only after the task is complete. If a task takes too long, the browser can’t do other tasks, such as processing user events. So after a time, it raises an alert like “Page Unresponsive”, suggesting killing the task with the whole page. Use-case 1: splitting CPU-hungry tasks Let’s say we have a CPU-hungry task. For example, syntax-highlighting (used to colorize code examples on this page) is quite CPU-heavy. To highlight the code, it performs the analysis, creates many colored elements, adds them to the document – for a large amount of text that takes a lot of time. While the engine is busy with syntax highlighting, it can’t do other DOM-related stuff, process user events, etc. It may even cause the browser to “hiccup” or even “hang” for a bit, which is unacceptable. We can avoid problems by splitting the big task into pieces. Highlight fir