我觉得按照 MDN 的说明,只需引用两段话:
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. Tasks added to the queue after the iteration begins will not run until the next iteration.
Each time a task exits, and the execution context stack is empty, each microtask in the microtask queue is executed, one after another. The difference is that execution of microtasks continues until the queue is empty—even if new ones are scheduled in the interim. In other words, microtasks can enqueue new microtasks and those new microtasks will execute before the next task begins to run, and before the end of the current event loop iteration.
获取一个宏任务(执行到栈空,而不是执行完队列里所有的)→ 执行微任务直到微任务队列为空 → 获取下一个宏任务
说白了就是任务队列在一次迭代中会无视后来队列的任务,而微任务会将其队列中的任务完全执行完(清空队列),微任务只要开始执行就到其队列为空为止。
所谓的一次迭代(Event Loop)应该是执行一组队列任务(栈空)。
注意到微任务开始执行是在运行栈空之前。
Ref:
In depth: Microtasks and the JavaScript runtime environment - Web APIs | MDN