← 回到书房大厅Esc

FROM THE BOOKSHELF / A PAGE TO KEEP

技术
66 分钟

宏任务、微任务与浏览器渲染循环

胡新宇

发布于 2026-05-21

系统讲解浏览器事件循环完整模型、Task Queue与Microtask Queue的清空时机、渲染时机优化及Node.js事件循环差异

宏任务、微任务与浏览器渲染循环

事件循环(Event Loop)是 JavaScript 实现异步非阻塞 I/O 的核心机制。它协调宏任务(macrotask)、微任务(microtask)和浏览器渲染三者的执行时序。理解事件循环对于优化页面性能、避免 UI 卡顿、正确预测代码执行顺序至关重要。Node.js 的事件循环与浏览器存在显著差异,本文将同时覆盖两种环境。


目录

  1. 事件循环的架构模型
  2. 宏任务队列详解
  3. 微任务队列与执行时机
  4. 浏览器渲染循环集成
  5. Node.js 事件循环的六个阶段
  6. 经典执行顺序题解析
  7. queueMicrotask 与调度策略
  8. 实战案例
  9. 深度追问
  10. 总结表格

1. 事件循环的架构模型

浏览器事件循环(HTML Living Standard §8.1.7)的核心流程:

┌─────────────────────────────────────────────┐
│                 Event Loop                    │
│                                              │
│  ┌─────────────┐                             │
│  │ Task Queue  │ ← setTimeout, I/O,          │
│  │ (macrotask) │   setInterval, UI events    │
│  └──────┬──────┘                             │
│         │ 取一个任务                          │
│         ▼                                    │
│  ┌─────────────┐                             │
│  │  执行任务    │ ← 同步代码执行               │
│  └──────┬──────┘                             │
│         │                                    │
│         ▼                                    │
│  ┌─────────────────┐                         │
│  │ Microtask Queue │ ← Promise.then,          │
│  │   (全部清空)    │   MutationObserver,      │
│  └──────┬──────────┘   queueMicrotask        │
│         │                                    │
│         ▼                                    │
│  ┌─────────────────┐                         │
│  │ Rendering       │ ← rAF, Style, Layout,   │
│  │ (可能跳过)      │   Paint, Composite      │
│  └─────────────────┘                         │
└─────────────────────────────────────────────┘
// 代码示例 1:基本执行顺序
console.log('1. 同步');

setTimeout(() => {
  console.log('4. 宏任务');
}, 0);

Promise.resolve().then(() => {
  console.log('3. 微任务');
});

console.log('2. 同步');

// 输出顺序:1 → 2 → 3 → 4

2. 宏任务队列详解

常见的宏任务源(Task Sources):

// 代码示例 2:不同宏任务的优先级
// setTimeout/setInterval — Timer 任务源
setTimeout(() => console.log('setTimeout'), 0);

// MessageChannel — 独立任务源
const channel = new MessageChannel();
channel.port1.onmessage = () => console.log('MessageChannel');
channel.port2.postMessage('');

// setImmediate (Node.js 专属)
if (typeof setImmediate !== 'undefined') {
  setImmediate(() => console.log('setImmediate'));
}

// requestAnimationFrame — 浏览器渲染前回调(不严格是宏任务)
requestAnimationFrame(() => console.log('rAF'));

// I/O 完成回调
// DOM 事件回调
// postMessage

setTimeout(fn, 0) 的真实延迟

// 代码示例 3:最小延迟测试
function measureMinDelay() {
  const timestamps = [];
  let count = 0;
  
  function tick() {
    timestamps.push(performance.now());
    if (++count < 20) {
      setTimeout(tick, 0);
    } else {
      // 计算实际间隔
      for (let i = 1; i < timestamps.length; i++) {
        console.log(`Tick ${i}: ${(timestamps[i] - timestamps[i-1]).toFixed(2)}ms`);
      }
    }
  }
  
  tick();
}
measureMinDelay();
// 嵌套 ≥ 5 次后,浏览器强制最小延迟 4ms(HTML 规范 §8.6)
// Chrome 中前 4 次约 1ms,之后约 4ms

3. 微任务队列与执行时机

微任务的关键特性:在当前任务结束后、下一个任务开始前,清空所有微任务

// 代码示例 4:微任务的递归执行
console.log('start');

Promise.resolve().then(() => {
  console.log('micro 1');
  Promise.resolve().then(() => {
    console.log('micro 2');
    Promise.resolve().then(() => {
      console.log('micro 3');
    });
  });
});

setTimeout(() => {
  console.log('macro 1');
}, 0);

console.log('end');

// 输出:start → end → micro 1 → micro 2 → micro 3 → macro 1
// 微任务会一直执行到队列清空!

微任务饥饿问题

// ⚠️ 危险:微任务可以阻塞渲染!
function microTaskStarvation() {
  let count = 0;
  
  function recursiveMicro() {
    if (count++ < 100000) {
      Promise.resolve().then(recursiveMicro);
    }
  }
  
  recursiveMicro();
  // 浏览器会卡死直到所有微任务完成!
  // 渲染和宏任务都无法执行
}

4. 浏览器渲染循环集成

// 代码示例 5:渲染时机验证
const box = document.getElementById('box');

// 这些 DOM 操作不会触发多次渲染
box.style.left = '0px';
box.style.left = '100px';
box.style.left = '200px';
// 只有最后一个值 '200px' 会被渲染

// requestAnimationFrame 在渲染前执行
requestAnimationFrame(() => {
  // 此时可以读取布局信息(无强制回流)
  const rect = box.getBoundingClientRect();
  // 修改样式在下一帧渲染
  box.style.transform = `translateX(${rect.left + 10}px)`;
});

完整的帧流水线

// 代码示例 6:一帧内的完整流程
// 1. 处理输入事件 (Input)
// 2. 执行 rAF 回调
// 3. 样式计算 (Style)
// 4. 布局 (Layout)
// 5. 绘制 (Paint)
// 6. 合成 (Composite)
// 7. 如果有空闲时间 → requestIdleCallback

requestAnimationFrame(() => {
  console.log('rAF - 渲染前');
  
  // 强制同步布局(Layout Thrashing)
  const height = box.offsetHeight; // 强制回流!
  box.style.height = height + 10 + 'px'; // 再次触发布局
});

// requestIdleCallback — 空闲时执行
requestIdleCallback((deadline) => {
  while (deadline.timeRemaining() > 5) {
    // 执行低优先级工作
    processNextItem();
  }
}, { timeout: 2000 }); // 最大延迟 2s

5. Node.js 事件循环的六个阶段

   ┌───────────────────────────┐
┌─►│         timers            │ ← setTimeout/setInterval 回调
│  └──────────┬────────────────┘
│  ┌──────────▼────────────────┐
│  │     pending callbacks     │ ← 系统级回调(TCP 错误等)
│  └──────────┬────────────────┘
│  ┌──────────▼────────────────┐
│  │       idle, prepare       │ ← 内部使用
│  └──────────┬────────────────┘
│  ┌──────────▼────────────────┐
│  │         poll              │ ← I/O 回调,可能阻塞
│  └──────────┬────────────────┘
│  ┌──────────▼────────────────┐
│  │         check             │ ← setImmediate 回调
│  └──────────┬────────────────┘
│  ┌──────────▼────────────────┐
│  │    close callbacks        │ ← socket.on('close')
│  └──────────┬────────────────┘
│             │
└─────────────┘
// 代码示例 7:Node.js 中的执行顺序差异
const fs = require('fs');

// 情况1:主模块中
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
// 顺序不确定!取决于 timer 精度

// 情况2:I/O 回调中
fs.readFile(__filename, () => {
  setTimeout(() => console.log('timeout'), 0);
  setImmediate(() => console.log('immediate'));
  // immediate 始终先于 timeout!(从 poll → check → timers)
});

// process.nextTick vs Promise
process.nextTick(() => console.log('nextTick'));
Promise.resolve().then(() => console.log('promise'));
// nextTick 先于 promise(nextTick 队列在微任务前清空)

6. 经典执行顺序题解析

// 代码示例 8:综合执行顺序
async function async1() {
  console.log('async1 start');        // 2
  await async2();
  console.log('async1 end');          // 6
}

async function async2() {
  console.log('async2');              // 3
}

console.log('script start');          // 1

setTimeout(function() {
  console.log('setTimeout');          // 8
}, 0);

async1();

new Promise(function(resolve) {
  console.log('promise1');            // 4
  resolve();
}).then(function() {
  console.log('promise2');            // 7
});

console.log('script end');            // 5

// 输出:script start → async1 start → async2 → promise1 → script end
//       → async1 end → promise2 → setTimeout

解析过程

// 代码示例 9:逐步分析
// 同步阶段:
// 1. console.log('script start')
// 2. 调用 async1() → console.log('async1 start')
// 3. await async2() → 执行 async2() → console.log('async2')
//    await 将后续代码放入微任务队列
// 4. new Promise executor → console.log('promise1')
//    resolve() → then 回调放入微任务队列
// 5. console.log('script end')

// 微任务阶段:
// 6. async1 的续体 → console.log('async1 end')
// 7. promise then → console.log('promise2')

// 宏任务阶段:
// 8. setTimeout → console.log('setTimeout')

7. queueMicrotask 与调度策略

// 代码示例 10:不同调度 API 的对比
// 微任务调度
queueMicrotask(() => console.log('queueMicrotask'));
Promise.resolve().then(() => console.log('Promise.then'));

// 宏任务调度
setTimeout(() => console.log('setTimeout'), 0);
const mc = new MessageChannel();
mc.port1.onmessage = () => console.log('MessageChannel');
mc.port2.postMessage('');

// 渲染相关调度
requestAnimationFrame(() => console.log('rAF'));
requestIdleCallback(() => console.log('rIC'));

// 执行顺序:
// queueMicrotask → Promise.then(微任务)
// → MessageChannel / setTimeout(宏任务,顺序可能变化)
// → rAF(渲染前)
// → rIC(空闲时)

scheduler.postTask (Scheduler API)

// Chrome 94+ 支持优先级调度
if ('scheduler' in globalThis) {
  scheduler.postTask(() => console.log('background'), { priority: 'background' });
  scheduler.postTask(() => console.log('user-visible'), { priority: 'user-visible' });
  scheduler.postTask(() => console.log('user-blocking'), { priority: 'user-blocking' });
  // 输出:user-blocking → user-visible → background
}

8. 实战案例

实战案例 1:长任务拆分避免卡顿

// 将耗时任务拆分到多个宏任务中
function processLargeArray(items, processFn, options = {}) {
  const { chunkSize = 100, onProgress, signal } = options;
  let index = 0;
  
  return new Promise((resolve, reject) => {
    function processChunk() {
      if (signal?.aborted) {
        reject(new DOMException('Aborted', 'AbortError'));
        return;
      }
      
      const start = performance.now();
      
      while (index < items.length) {
        processFn(items[index], index);
        index++;
        
        // 每处理 chunkSize 个或超过 5ms,让出主线程
        if (index % chunkSize === 0 || performance.now() - start > 5) {
          onProgress?.(index / items.length);
          // 使用 MessageChannel 比 setTimeout 更快
          const mc = new MessageChannel();
          mc.port1.onmessage = processChunk;
          mc.port2.postMessage('');
          return;
        }
      }
      
      onProgress?.(1);
      resolve();
    }
    
    processChunk();
  });
}

// 使用
const items = new Array(100000).fill(null).map((_, i) => i);
await processLargeArray(items, (item) => {
  // 耗时处理
  Math.sqrt(item) * Math.random();
}, {
  chunkSize: 500,
  onProgress: (p) => console.log(`${(p * 100).toFixed(1)}%`)
});

实战案例 2:批量 DOM 更新优化

class BatchDOMUpdater {
  #pending = [];
  #scheduled = false;
  
  schedule(updateFn) {
    this.#pending.push(updateFn);
    
    if (!this.#scheduled) {
      this.#scheduled = true;
      // 在下一帧统一执行所有 DOM 更新
      requestAnimationFrame(() => {
        // 先执行所有读操作
        const reads = this.#pending.filter(fn => fn.type === 'read');
        const writes = this.#pending.filter(fn => fn.type === 'write');
        
        reads.forEach(fn => fn());
        writes.forEach(fn => fn());
        
        this.#pending = [];
        this.#scheduled = false;
      });
    }
  }
  
  read(fn) {
    fn.type = 'read';
    this.schedule(fn);
  }
  
  write(fn) {
    fn.type = 'write';
    this.schedule(fn);
  }
}

// 使用:避免 Layout Thrashing
const batcher = new BatchDOMUpdater();

elements.forEach(el => {
  batcher.read(() => {
    const height = el.offsetHeight; // 批量读
    batcher.write(() => {
      el.style.height = height * 2 + 'px'; // 批量写
    });
  });
});

实战案例 3:Promise 微任务与 Vue nextTick

// Vue 2/3 中 nextTick 的简化实现
const callbacks = [];
let pending = false;

function nextTick(cb) {
  return new Promise((resolve) => {
    callbacks.push(() => {
      if (cb) {
        try { cb(); resolve(); }
        catch (e) { reject(e); }
      } else {
        resolve();
      }
    });
    
    if (!pending) {
      pending = true;
      // 优先使用微任务
      Promise.resolve().then(flushCallbacks);
    }
  });
}

function flushCallbacks() {
  pending = false;
  const copies = callbacks.slice();
  callbacks.length = 0;
  for (const fn of copies) {
    fn();
  }
}

9. 深度追问

Q1:为什么 Vue 从 macrotask 切换到 microtask 实现 nextTick?

Vue 2.5+ 将 nextTick 实现从 MessageChannel(宏任务)切换为 Promise.then(微任务),原因是宏任务在状态变更和渲染之间有一帧延迟,导致闪烁。微任务在渲染前执行,可以在同一帧内完成状态更新和 DOM 修改。

Q2:requestAnimationFrame 的回调在什么阶段执行?

rAF 在浏览器准备绘制新一帧时执行,位于样式计算和布局之前。如果页面在后台(不可见),rAF 会暂停调用以节省资源。注意:rAF 并非严格的宏任务或微任务,它有自己独立的回调队列。

Q3:await 后的代码为什么比 .then 晚一个微任务?

在早期规范中,await 需要额外的 Promise 包装(多一个微任务 tick)。ES2020 优化了这一点:如果 await 的值已经是 fulfilled Promise,V8 可以直接安排微任务而不需要额外包装。这意味着现代引擎中 await 和 .then 的时序差异已经消除。


10. 总结表格

任务类型API执行时机使用场景
宏任务setTimeout下一轮事件循环延迟执行、长任务拆分
宏任务MessageChannel下一轮(比 setTimeout 快)内部调度
宏任务setImmediatecheck 阶段(Node.js)I/O 后立即执行
微任务Promise.then当前任务后、渲染前异步流程控制
微任务queueMicrotask同上显式微任务调度
微任务MutationObserver同上DOM 变更监听
渲染requestAnimationFrame渲染前动画、DOM 测量
空闲requestIdleCallback帧间空闲低优先级工作
浏览器 vs Node.js浏览器Node.js
微任务清空时机每个宏任务后每个阶段切换时
nextTick不存在优先于微任务
setImmediate不存在check 阶段
rAF渲染前不存在
最小 setTimeout 延迟4ms(嵌套≥5次)1ms

下一篇:07. Promise A+ 规范实现