The Event Loop

The event loop is how JavaScript checks and executes code. It is the way that events are collected, queued and executed. In theory is it pretty straightforward to understand, but it took me a while to wrap my head around it so i'll try to explain it in a way that makes sense to me.

The Stack

JavaScript is single threaded. By this, I mean that only 1 thing happens at a time. When you write 10 functions, each of the functions calls will be added to the "stack", determining when the function will be executed. When a function is executed, it is removed from the top of the stack and the next function is executed.

Event Queue

This doesn't sound too complicated. However, let's say in a list of 10 functions, a couple of them are asynchronous, meaning that they can possibly take a while to complete. These asynchronous operations perform their actions in the background and get added to the "event queue". The event queue only releases tasks when the stack is empty allowing synchronous operations to not get blocked by Web API operations.

Let's try an attempt at an analogy... So, imagine you are eating lunch and for some reason you fancy a cup of coffee at the same time. You can only eat one bite at a time. You go and put the kettle on but your priority is to finish your food. The way the event loop works means that you would keep checking to see if there is food on your plate. Once the food is finished, then you would go and get your coffee. Food here representing the call stack, and the coffee the event queue.

Micro and Macro tasks

Going into a bit more depth, asynchronous actions are split into 2 main groups. These are Microtasks and Macrotasks. Both are asynchronous but Microtasks take priority in the event queue and therefore get pushed to the stack first.

Microtasks include promises and DOM observers, and Macrotasks include Web API's such as setTimeout and setInterval.

Given this, if you call a setTimeout then 2 promises, the promises will be added to the call stack first and the setTimeout will be added after.