元素码农
基础
UML建模
数据结构
算法
设计模式
网络
TCP/IP协议
HTTPS安全机制
WebSocket实时通信
数据库
sqlite
postgresql
clickhouse
后端
rust
go
java
php
mysql
redis
mongodb
etcd
nats
zincsearch
前端
浏览器
javascript
typescript
vue3
react
游戏
unity
unreal
C++
C#
Lua
App
android
ios
flutter
react-native
安全
Web安全
测试
软件测试
自动化测试 - Playwright
人工智能
Python
langChain
langGraph
运维
linux
docker
工具
git
svn
🌞
🌙
目录
▶
执行上下文
▶
创建过程
变量对象
作用域链
This绑定
▶
执行阶段
执行栈机制
词法环境
闭包实现
▶
内存管理
▶
内存模型
堆栈结构
内存分配
内存泄漏
▶
回收机制
标记清除
引用计数
代际假说
▶
事件循环
▶
运行机制
调用栈解析
任务队列
微任务优先
▶
异步处理
Promise原理
Async/Await
Web Workers
▶
原型系统
▶
原型基础
原型链机制
__proto__属性
构造函数
▶
类继承
ES6类语法
继承实现
super关键字
▶
类型系统
▶
基础类型
类型检测
装箱拆箱
类型转换
▶
高级类型
Symbol特性
BigInt实现
类型数组
▶
作用域与闭包
▶
作用域体系
词法作用域
动态作用域
作用域链生成
▶
闭包机制
闭包存储结构
IIFE模式原理
内存泄漏防范
发布时间:
2025-03-22 11:38
↑
☰
# JavaScript微任务优先级机制 微任务(Microtask)在JavaScript事件循环中具有特殊的优先级。本文将深入讲解微任务的优先级机制、执行顺序和实践应用。 ## 微任务优先级基本原理 在JavaScript事件循环中,微任务具有比宏任务更高的执行优先级。每当一个宏任务执行完成后,事件循环会先清空微任务队列,然后再执行下一个宏任务。 ```javascript console.log('Start'); // 1 setTimeout(() => { console.log('Timeout 1'); // 5 Promise.resolve().then(() => { console.log('Timeout 1 - Promise'); // 6 }); }, 0); Promise.resolve().then(() => { console.log('Promise 1'); // 3 setTimeout(() => { console.log('Promise 1 - Timeout'); // 7 }, 0); }); queueMicrotask(() => { console.log('Microtask 1'); // 2 }); Promise.resolve().then(() => { console.log('Promise 2'); // 4 }); console.log('End'); // 1 // 输出顺序: // Start // End // Microtask 1 // Promise 1 // Promise 2 // Timeout 1 // Timeout 1 - Promise // Promise 1 - Timeout ``` ## 微任务类型及优先级 ### 1. Promise处理 ```javascript class PromiseHandler { static createMicroTasks() { Promise.resolve('Task 1') .then(result => { console.log(result); // 1 return 'Task 2'; }) .then(result => { console.log(result); // 2 return Promise.resolve('Task 3'); }) .then(result => { console.log(result); // 3 }); } static handleRejection() { Promise.reject('Error') .catch(error => { console.log('Caught:', error); // 微任务中处理错误 return 'Recovered'; }) .then(result => { console.log('Then:', result); }); } } ``` ### 2. MutationObserver ```javascript class DOMObserver { constructor() { this.observer = new MutationObserver(mutations => { // 作为微任务执行 mutations.forEach(mutation => { console.log('DOM changed:', mutation.type); }); }); } observe(target) { this.observer.observe(target, { attributes: true, childList: true, subtree: true }); } disconnect() { this.observer.disconnect(); } } ``` ### 3. Process.nextTick (Node.js) ```javascript class NodeMicrotasks { static schedule() { process.nextTick(() => { console.log('NextTick 1'); // 1 - 最高优先级 }); Promise.resolve().then(() => { console.log('Promise'); // 2 }); process.nextTick(() => { console.log('NextTick 2'); // 1 - 最高优先级 }); } } ``` ## 微任务队列管理 ### 1. 队列实现 ```javascript class MicrotaskQueue { constructor() { this.tasks = []; this.isProcessing = false; } enqueue(task) { this.tasks.push(task); if (!this.isProcessing) { this.processQueue(); } } async processQueue() { this.isProcessing = true; while (this.tasks.length > 0) { const task = this.tasks.shift(); try { await task(); } catch (error) { console.error('Task error:', error); } } this.isProcessing = false; } } ``` ### 2. 优先级控制 ```javascript class PriorityMicrotaskQueue { constructor() { this.highPriority = []; this.normalPriority = []; this.lowPriority = []; } addTask(task, priority = 'normal') { switch (priority) { case 'high': queueMicrotask(() => this.highPriority.push(task)); break; case 'normal': Promise.resolve().then(() => this.normalPriority.push(task)); break; case 'low': setTimeout(() => this.lowPriority.push(task), 0); break; } } async processTasks() { // 按优先级执行任务 while (this.highPriority.length) { await this.highPriority.shift()(); } while (this.normalPriority.length) { await this.normalPriority.shift()(); } while (this.lowPriority.length) { await this.lowPriority.shift()(); } } } ``` ## 实际应用场景 ### 1. 状态更新 ```javascript class StateManager { constructor() { this.state = {}; this.subscribers = []; } setState(newState) { const oldState = {...this.state}; this.state = {...this.state, ...newState}; // 使用微任务通知状态更新 queueMicrotask(() => { this.subscribers.forEach(subscriber => { subscriber(this.state, oldState); }); }); } subscribe(callback) { this.subscribers.push(callback); return () => { const index = this.subscribers.indexOf(callback); if (index > -1) { this.subscribers.splice(index, 1); } }; } } ``` ### 2. DOM更新 ```javascript class DOMUpdater { constructor() { this.pendingUpdates = new Set(); } scheduleUpdate(element, updateFn) { this.pendingUpdates.add({element, updateFn}); // 使用微任务批量处理DOM更新 Promise.resolve().then(() => { this.flushUpdates(); }); } flushUpdates() { this.pendingUpdates.forEach(({element, updateFn}) => { try { updateFn(element); } catch (error) { console.error('Update failed:', error); } }); this.pendingUpdates.clear(); } } ``` ### 3. 错误处理 ```javascript class ErrorBoundary { constructor() { this.errorHandlers = []; } addErrorHandler(handler) { this.errorHandlers.push(handler); } handleError(error) { // 使用微任务处理错误,避免阻塞主流程 Promise.resolve().then(() => { this.errorHandlers.forEach(handler => { try { handler(error); } catch (e) { console.error('Error handler failed:', e); } }); }); } } ``` ## 性能优化 ### 1. 批量处理 ```javascript class BatchProcessor { constructor() { this.batch = []; this.processing = false; } add(item) { this.batch.push(item); if (!this.processing) { this.scheduleProcessing(); } } scheduleProcessing() { this.processing = true; queueMicrotask(() => { this.processBatch(); this.processing = false; }); } processBatch() { const items = this.batch; this.batch = []; // 批量处理收集的项目 items.forEach(item => { try { this.processItem(item); } catch (error) { console.error('Processing failed:', error); } }); } processItem(item) { // 具体的处理逻辑 } } ``` ### 2. 防抖节流 ```javascript class EventHandler { constructor() { this.debounceTimeout = null; this.throttleLastRun = 0; } debounce(fn, delay) { return (...args) => { clearTimeout(this.debounceTimeout); this.debounceTimeout = setTimeout(() => { // 使用微任务执行防抖后的函数 queueMicrotask(() => fn.apply(this, args)); }, delay); }; } throttle(fn, limit) { return (...args) => { const now = Date.now(); if (now - this.throttleLastRun >= limit) { this.throttleLastRun = now; // 使用微任务执行节流后的函数 queueMicrotask(() => fn.apply(this, args)); } }; } } ``` ## 最佳实践 ### 1. 合理使用微任务 ```javascript class TaskManager { static handleTask(task, isUrgent = false) { if (isUrgent) { // 紧急任务使用微任务 queueMicrotask(task); } else { // 非紧急任务使用宏任务 setTimeout(task, 0); } } static chainTasks(tasks) { return tasks.reduce((promise, task) => { return promise.then(() => { return new Promise(resolve => { queueMicrotask(() => { task(); resolve(); }); }); }); }, Promise.resolve()); } } ``` ### 2. 错误处理 ```javascript class MicrotaskError { static handleAsync(fn) { return (...args) => { try { const result = fn.apply(this, args); if (result && typeof result.then === 'function') { return result.catch(error => { // 使用微任务处理异步错误 queueMicrotask(() => { console.error('Async error:', error); throw error; }); }); } return result; } catch (error) { // 使用微任务处理同步错误 queueMicrotask(() => { console.error('Sync error:', error); throw error; }); } }; } } ``` ## 总结 微任务优先级机制是JavaScript事件循环中的重要特性,它确保了: 1. 高优先级任务的及时执行 2. DOM更新的一致性 3. 错误处理的可靠性 4. 状态管理的准确性 在实际开发中,我们应该: 1. 理解微任务的执行时机和优先级 2. 合理使用不同类型的微任务 3. 注意微任务队列的管理和优化 4. 实现高效的任务调度机制