Event Loop - alexanderteplov/computer-science GitHub Wiki
Event loop is a thing making all more complicated and more simple at the same time.
It's an ugly child of a single-threaded language. But like a disabled person can create a beautiful symphony, it orchestrates parallel computations with surprising grace.
Generally it's a cycle and can be implemented like this:
while (true) {
gueue = getNextQueue();
task = queue.pop();
execute(task);
while (microtaskQueue.hasTasks())
doMicrotask();
if (isRepaintTime()) {
animationTasks = animationQueue.copyTasks();
for (task in animationTasks)
doAnimationsTask(task);
repaint();
}
}Or be represented as in this simplified diagram:
-
Task Queues. Everything, except microtasks, is a task. There are several task queues with different priorities. Like:
<script>Timers- user input (mouse, keyboard events, etc.)
- any unspecified callbacks
-
Microtask Queue. There are only a few things you can do to create a microtask:
- any
Promise -
MutationObserver APIcallback queueMicrotask()
- any
- RequestAnimationFrame task Queue. It fires at a specific time repeatedly (mostly every 16 ms).
- First, the browser queues scripts from
<script>or<link>tags in the Task queue. Then starts to execute them one by one. Any function it meets during execution is placed into the Call Stack and removed from it after reaching either the return statement or their end. - Any callback met here, such as
setTimeoutcallback or user input handler, browser queues into an according Task Queue. Any Promise met the browser queues into Microtasks Queue. And call of therequestAnimationFrame- into RequestAnimationFrame task Queue. - After the Call Stack has been emptied the browser pop one task from a Task Queue. There works a FIFO rule within some particular Task Queue but the browser can choose the next Task Queue in any order. Then, the browser executes a task the same way as with the script above (at 1.). It queues anything needed as in 2.
- If the Microtask Queue is not empty, the browser will empty it executing microtasks one by one, after any finished task.
- The browser idles for a while.
- When some time is reached the browser pop the first
requestAnimationFramecallback from its queue, executes as other tasks and then starts the render process.