jQuery .queue() / .dequeue() 讓多元素、多步驟動畫/異步操作**脫離巢狀回調**,以**線性陣列**聲明流程,極大提升可讀性與可維護性。
$(el).queue(name, fnArray):將函數陣列推入指定隊列 (預設 "fx" 動畫隊列)。$(el).dequeue(name):取出並執行隊列**首個**函數,**函數內部必須呼叫 dequeue 觸發下一步** (或回傳 Promise/動畫自動觸發)。$(document) 作為全域隊列載體。// 1. 定義線性步驟陣列
var steps = [
function() { $("#block1").animate({left: "+=100"}, 500, next); },
function() { $("#block2").animate({left: "+=100"}, 500, next); },
function() { $("#block1").animate({left: "+=100"}, 500, next); },
function() { $("#block2").animate({left: "+=100"}, 500, next); },
function() { $("#block1").animate({left: "+=100"}, 500, next); },
function() { alert("動畫結束"); }
];
// 2. 統一回調觸發下一步
function next() { $(document).dequeue("myAnim"); }
// 3. 啟動
$(document).queue("myAnim", steps);
next(); // 執行第一步
// 清空隊列 (取消剩餘動畫)
$(document).queue("myAnim", []);
// 動態追加步驟
$(document).queue("myAnim", function() { console.log("額外步驟"); $(document).dequeue("myAnim"); });
// 獲取隊列長度
var len = $(document).queue("myAnim").length;
dequeue,避免 .then().then() 巢狀。dequeue 進入下一步。class SimpleQueue {
constructor() { this.q = []; this.running = false; }
add(fn) { this.q.push(fn); if (!this.running) this.next(); }
next() { if (this.q.length === 0) return; this.running = true; this.q.shift()(() => this.next()); }
}
// 用法: const q = new SimpleQueue(); q.add(() => fetch(...).then(q.next)); ...