jQuery 的 queue() / dequeue() 是處理異步序列(動畫、AJAX、定時任務)的核心機制。本文深入剖析其工作原理,展示實戰應用模式,並提供原生 JavaScript 模擬實現。
"fx"(動畫專用)queue(fn):將函數推入隊列尾部dequeue():取出隊首函數並執行,內部通常調用 shift()dequeue(),後續函數永不執行需求:兩個 div 依次變色動畫,按順序執行。
<div id="block1">div 1</div>
<div id="block2">div 2</div>
<script>
var FUNC = [
function() { $("#block1").animate({color: "blue"}, aniCB); },
function() { $("#block2").animate({color: "red"}, aniCB); },
function() { $("#block1").animate({color: "yellow"}, aniCB); },
function() { $("#block2").animate({color: "grey"}, aniCB); },
function() { $("#block1").animate({color: "green"}, aniCB); },
function() { alert("動畫結束"); }
];
var aniCB = function() {
$(document).dequeue("myAnimation"); // 執行隊列下一幀
};
$(document).queue("myAnimation", FUNC); // 注入隊列
// aniCB(); // 手動啟動第一幀(或在隊列首函數內自動觸發)
</script>
$(document).queue("myAnimation", []) 清空隊列$(document).queue("myAnimation", fn) 加入尾部多個 AJAX 請求需順序執行,傳統回調地獄難維護。隊列模式優雅解決:
var ajaxQueue = [
function() { $.get('/api/1', next); },
function() { $.get('/api/2', next); },
function() { $.get('/api/3', next); }
];
function next() {
$(document).dequeue("ajaxSeq");
}
$(document).queue("ajaxSeq", ajaxQueue);
next(); // 啟動首個
理解底層原理,攤開 jQuery 黑盒:
function Queue() {
this.a = []; // 函數/任務陣列
this.t = null; // 定時器句柄
}
Queue.prototype = {
// 入隊
queue: function(s) {
var self = this;
this.a.push(s);
this.hold(); // 啟動/重置執行調度
return this; // 鏈式調用
},
// 調度器:異步微任務觸發 dequeue
hold: function() {
var self = this;
clearTimeout(this.t);
this.t = setTimeout(function() {
console.log("Queue start!", self.a);
self.dequeue();
}, 0);
},
// 出隊執行
dequeue: function() {
var s = this.a.shift(), self = this;
if (s) {
console.log("s:", s);
// 模擬異步耗時 s 毫秒
setTimeout(function() {
console.log("end:", s);
self.dequeue(); // 遞歸處理下一個
}, s);
}
}
};
// 使用:鏈式入隊,參數為模擬耗時(ms)
var q = new Queue()
.queue(500)
.queue(200)
.queue(400)
.queue(1500)
.queue(300)
.queue(2000);
setTimeout(fn, 0) 將 dequeue 推到下一事件循環,避免阻塞主線程dequeue() 推進隊列queue() 返回 this,支持流式調用s 既可為函數,也可為延遲時間(示例簡化為時間)fx 隊列.animate() 內部自動 queue('fx', fn)dequeue('fx') 驅動下一幀.stop(true) 清空隊列並跳至最後狀態.finish() 立即完成當前動畫並清空隊列"myAnimation")隔離業務,避免污染 "fx"dequeue(),否則隊列卡死try...catch 並確保 finally 中 dequeue().queue(fn) 形式插入單個函數,比操作陣列更直觀Queue/Dequeue 是 jQuery 異步編程的基石。掌握其「入隊、出隊、遞歸驅動」核心模式,不僅能優雅處理動畫/AJAX 序列,更能深度理解前端異步調度本質。原生模擬實現進一步揭示了事件循環與微任務調度的底層邏輯。