Mocrotasks & Microtasks

97 阅读2分钟

参考网站

Event Loop

Browser JavaScript execution flow, as well as in Node.js, is based on an event loop.

浏览器中的Javascript执行流,就像在node.js中一样,基于事件循环

Understanding how event loop works is important for optimizations, and sometimes for the right architecture.

对于优化和一些正确的建筑学,明白事件循环是如何工作的是非常重要的

In this chapter we first cover theoretical details about how things work, and then see practical applications of that knowledge.

这一节我们首页全面了解关于事件循环如何工作的理论详情,并看一些实际操作的知识;

Event Loop

The event loop concept is very simple. There’s an endless loop, where the JavaScript engine waits for tasks, executes them and then sleeps, waiting for more tasks.

事件循环的概念非常简单。这里有一个不会结束的循环,当javascript 引擎等待任务时,执行它并休眠,等待更多的任务;

The general algorithm of the engine:

  1. While there are tasks:
    • execute them, starting with the oldest task.
  2. Sleep until a task appears, then go to 1.

引擎的常用逻辑:

  1. 当有任务时:
    • 执行任务,从最旧的任务开始;
  2. 休眠直到有任务出现,回到步骤1;

触发Macrotasks

  • 执行script
  • setTimeout/setInterval
  • 事件回调

关于任务的两点描述

  1. Rendering never happens while the engine executes a task. It doesn’t matter if the task takes a long time. Changes to the DOM are painted only after the task is complete.
  2. 当引擎执行任务时,是不会进行渲染的,无论任务需要多小时间才能完成,Dom的变化需要在任务完成后才会显示出来;
  3. If a task takes too long, the browser can’t do other tasks, such as processing user events. So after a time, it raises an alert like “Page Unresponsive”, suggesting killing the task with the whole page. That happens when there are a lot of complex calculations or a programming error leading to an infinite loop.
  4. 如果一个任务使用太长的时候,浏览器不能做其它任务,例如处理用户的事件。 当一段时间之后,它会显示一个弹窗"页面没有响应",支持在整个页面kill打死这个任务。 它通常会在一系列复杂的计算或者程序错误时出现的死循环。