Javascript queues (event loop)

MD
R
Markdown

Execution order: sync queue, promise queue, timeout queue (FIFO) one (tab) thread === one call stack === one thing at a time Based on: https://hackernoon.com/run-javascript-run https://v8.dev/

1Always the same order: CONSOLE, PROMISE, TIMEOUT
2
3```js
4Promise.resolve("1. promise").then((res) => console.log(res));
5setTimeout(() => console.log("2. timeout"));
6console.log("3. console");
7```
8
9
10Queues (priority):
11JS Engine: Call Stack (sync functions, browser API functions)
12Event Loop: MicroTask Queue (Promises, async functions)
13Event Loop: Task Queue (setTimeout, setInterval)
14
15
16Why?
17 ==== JS Engine in Control (JS Engine Synchronous Call Stack Full) ====
181. JS Engine:  Code is sent to Call Stack (JS Engine) and executed sequentially (P1)
192. JS Engine: setTimeout sends a callback function to the Event Loop: Task Queue (P3).
203. JS Engine: console.log is a Browser API sync function call is processed immediatelly (P1)
214. JS Engine: Promise.resolve(...).then(...) sends the callback to the Event Loop Microtask Queue. (P2)
22 ==== Event Loop in Control (JS Engine Synchronous Call Stack Empty) ====
235. Event Loop: checks Microtask Queue and finds there callback from the resolved promise and sends it to the JS Engine: Call Stack  (P2)
246. Event Loop: Microtask Queue is empty, JS Engine Call Stack is empty, it is Event Loop Task Queue turn now. (P3).
257. Event Loop: finds a timeout callback in the Task Queue (P3).
26 ==== JS Engine in Control (Event Loop Call Stacks Empty) ====
27
28
29Some notes:
30JS Multi-thread Process: Web Workers API (Browser), Child Processes (Node.js)
31Browser DevTools is a different Thread Process
32
33JavaScript Engine: compiles, optimizes, and executes code, handles memory allocation and garbage collection
34Event Loop: orchestrates and distributes the work, enables asynchronicity.
35Browser Web API / Node.js API: allows communication with things located outside of the Runtime (e.g system timers, file system, HTTP, address bar, DOM, etc.)
36
37Browser API Stuff: setTimer, fetch,
38JS Engine Stuff (ECMAScript): Date, For Loops, String, Number
39
40JS Engine only executes things in the Call Stack (each item in the stack is a function call)
41JS Engine won't stop popping frames from the Call Stack until it is empty. And it won't allow any interruptions from outside until it is done.
42
43EventLoop:
44
45```js
46while (true) {
47  if (allDone()) {
48    const thingsToDo = getThingsToDo();
49    doThings(thingsToDo);
50  }
51}
52```
53
54Event Loop In the Browser
55Window Event Loop, Worker Event Loop, ServiceWorker Event Loop, Worklet Event Loop
56
57Event Loop QueuesL task queue, and microtask queue (async, promises) . (role: postpone code execution for later)
58
59Order of execution:
601. Event Loop: watches the Task Queue
612. Event Loop: Finds new records on Task Queue, moves them to the Call Stack (JS Engine) *FIFO, empties the stack
623. JS Engine: takes over and doing its job until it empties the Call Stack
634. Event Loop: watches microtask queue(s) for promises
645. Event Loop: Finds new records on microtask queue, moves them to the Call Stack (JS Engine) *FIFO, empties the stack
655.1 ** Event Loop:  microtask code can push another microtask in the queue and it will be executed during the same iteration (right here). **
666. JS Engine Call Stack and Event Loop Microtask Queue are empty.
677. Event Loop: gets back to watch Task Queue. 1.
68
69Dequeing:
701. Event Loop: mark the newest tail task, start dequeuing tasks (head to tail) and pushing code to the JS Engine Call Stack until it reaches marked task. (new tasks are being added to the queue every ms)
71
72Problems:
731. StackOverflow
741.1 Every time we push a new item on the Call Stack, the Engine will immediately switch to it, won't be able to pop out any items as we are always sending new items on every CPU cycle
75

Created on 9/11/2021