queue() 與 dequeue() 是一組很有用的方法,特別適合處理「必須依序執行、且每個都要花一點時間」的一系列函式,例如動畫、Ajax、計時器等。
queue() 把函式(通常是一個函式陣列)加入佇列。dequeue() 取出並執行佇列中的第一個函式(內部用 shift() 取出)。這意味著兩件事:每次 dequeue 執行的是不同的函式;以及如果不呼叫 dequeue,佇列中的下一個函式永遠不會執行。
補充一個常被忽略的細節:對元素呼叫 animate() 時,jQuery 內部會把動畫加入名為 fx 的佇列。若要多個元素依次執行動畫,就必須自己安排佇列。
<div id="block1">div 1</div>
<div id="block2">div 2</div>
<script type="text/javascript">
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("動畫結束"); }
];
// 每個動畫做完就 dequeue,啟動下一個
var aniCB = function () {
$(document).dequeue("myAnimation");
};
$(document).queue("myAnimation", FUNC); // 把整個佇列掛在 document 上
aniCB(); // 啟動第一個
</script>
流程是:建立函式陣列 → 定義「做完就 dequeue」的回呼 → 把陣列放進名為 myAnimation 的佇列 → 呼叫第一次來啟動。把佇列掛在 document 上只是為了方便,實際上任選一個元素都可以。
// 清空佇列
$(document).queue("myAnimation", []);
// 在尾端追加一個新步驟
$(document).queue("myAnimation", function () {
alert("動畫真的結束了!");
});
需要一串 Ajax 依序執行、每個都等前一個結束才開始時,傳統做法是用回呼函式一層層嵌套,寫起來非常痛苦。改用佇列就乾淨多了:把每個請求放進佇列,並在每次 success 回呼中 dequeue。
var tasks = [
function () { $.getJSON('/api/step1', next); },
function () { $.getJSON('/api/step2', next); },
function () { $.getJSON('/api/step3', next); }
];
function next() { $(document).dequeue("myAjax"); }
$(document).queue("myAjax", tasks);
$(document).dequeue("myAjax");
更好的現代做法是 async/await,程式碼會像同步一樣直讀:
async function run() {
const a = await fetch('/api/step1').then(r => r.json());
const b = await fetch('/api/step2').then(r => r.json());
const c = await fetch('/api/step3').then(r => r.json());
return [a, b, c];
}
function Queue() {
this.a = []; // 任務佇列
this.t = null; // 計時器 handle
}
Queue.prototype = {
queue: function (s) {
this.a.push(s);
this.hold();
return this;
},
hold: function () {
var self = this;
clearTimeout(this.t);
// 用 setTimeout 0 讓啟動延到下一輪,避免連續 push 時重複啟動
this.t = setTimeout(function () {
console.log("Queue start! ", self.a);
self.dequeue();
}, 0);
},
dequeue: function () {
var s = this.a.shift();
var self = this;
if (s) {
console.log("s: " + s);
setTimeout(function () {
console.log("end: " + s);
self.dequeue(); // 這個任務結束,接著下一個
}, s);
}
}
};
var a = new Queue()
.queue(500).queue(200).queue(400).queue(1500).queue(300).queue(2000);
這段實作抓住了佇列的兩個關鍵:shift() 取出頭部元素(先進先出),以及每個任務結束後才 dequeue 下一個。範例中用 setTimeout 的延遲時間模擬任務耗時。
若需求是「一連串非同步任務依序執行」,用 Promise 鏈或 async/await 會比佇列語意更清楚:
// Promise 鏈
tasks.reduce((p, task) => p.then(task), Promise.resolve());
// 中止後續任務:用一個旗標
var cancelled = false;
async function run() {
for (const task of tasks) {
if (cancelled) break;
await task();
}
}
jQuery 的 queue 在現代專案中主要還是用於動畫序列;非同步流程建議交由 Promise 機制處理,可讀性與錯誤處理都更好。