39 lines
1.7 KiB
Markdown
39 lines
1.7 KiB
Markdown
# The Event Loop
|
|
|
|
The event loop is how javascript code is being run in the browser.
|
|
|
|
The call stack is the order of code. JavaScript is a single-threaded language, which means that only one thing can be run at the time.
|
|
|
|
The queue is the order of which the code gets run.
|
|
|
|
Macrotasks and Microtasks.
|
|
|
|
You can block the single call stack by looping the callstack and then freeze the renders of the UI.
|
|
|
|
Using Microtasks(I.E Promises), you can kind of stop the blocking, but not entirely. You can flood the microtaskqueue with many concurrent microtask promises. Microtasks is also called the VIP queue.
|
|
|
|
When yielding to the event loop you will mix the callstack, microtask and macrotask and kind of trick javascript to render more frequent. Making it a smoother UI experience. This is great for handling hard computational data, large datasets, formatting code or processing datastreams.
|
|
|
|
Yielding can be done by wrapping your promises in a setTimeout(function, 0) inside the concurrenct async loop. This will add to the macrotask loop which clears the queue regularly and lets the UI render.
|
|
|
|
By using setTimeout you add a MacroTask in between the microtasks queue before adding a new to the macrotask(vip) queue. This opens the callstack for a render.
|
|
|
|
The best way to create a yielding function in modern JavaScript
|
|
|
|
```javascript
|
|
// A helper function you can paste into your utils
|
|
const yieldToMain = () => new Promise(resolve => setTimeout(resolve, 0));
|
|
|
|
// Usage inside your heavy AI loop
|
|
async function processLargeData() {
|
|
for (let i = 0; i < 10000; i++) {
|
|
doHeavyMath(i); // Example function
|
|
|
|
// Yield every 50 iterations to keep UI buttery smooth (60fps)
|
|
if (i % 50 === 0) {
|
|
await yieldToMain();
|
|
}
|
|
}
|
|
}
|
|
```
|