javascriptevent-loop

Confused about how event loop fetch tasks from task queue


Recently I saw the event loop session shared by Jake Archibald. As he mentioned in the time 27:55 of the video, it seems the event loop get task from queue one item per round

enter image description here

However, we I read the document on mozilla In depth: Microtasks and the JavaScript runtime environment, it says this:

When executing tasks from the task queue, the runtime executes each task that is in the queue at the moment a new iteration of the event loop begins.

It seems all the items in the queue will be fetched when the round began

So which one is correct? 1 item per round or all existing items per round?


Solution

  • It's "one item per round", using the specs wordings:

    1. If the event loop has a task queue with at least one runnable task, then:

    [note] Remember that the microtask queue is not a task queue, so it will not be chosen in this step. However, a task queue to which the microtask task source is associated might be chosen in this step. In that case, the task chosen in the next step was originally a microtask, but it got moved as part of spinning the event loop.

    So the only task that is ran in one event-loop's "round", is "the first runnable task in taskQueue".

    The MDN article should be updated since indeed that wording is confusing. (Arguably, it's not the only confusing part of that article, since tasks do not necessarily execute JS, and microtasks are not in direct opposition of tasks, since they'll also be executed between some callbacks).