JS Event Loop

It’s an integral part of understanding how JS works under the hood. Core runtime JS framework consists of: Runtime Stack, WebAPI, Task Queue

1. Initial Program State: Currently executing function is in stack

2. SetTimeout encountered

SetTimeout is provided by browser WebAPIs to support concurrency in JS and maintained separately from the runtime stack. A timer is started separately

Event Loop 2

3. Runtime Stack and WebAPI executing parallely

As timer is running in WebAPI, the runtime stack will continue executing the rest of the function.

Event Loop 3

4. Timer finished

Once the timer goes off, WebAPI will push the timer callback to task queue

Event Loop 4

5. Event Loop

At this point, JS event loop checks
a. If runtime stack has anything, execute it
b. Pop the next function from task queue and push it to runtime stack.

Event Loop 5

This exercise shows the execution context when timeout was set to 5000. It would be interesting to see the same context when timer is set to 0s.

Source: What the heck is the event loop