佇列 是「先進先出」(FIFO, First-In-First-Out)的線性結構,僅允許隊尾插入(enqueue)、隊首刪除。JavaScript 單執行緒特性使得非同步任務排程極度依賴佇列機制,jQuery 動畫佇列即為經典應用。
function Queue() {
this.dataStore = [];
this.enqueue = enqueue; // 隊尾加入
this.dequeue = dequeue; // 隊首移除
this.first = first; // 查看隊首
this.end = end; // 查看隊尾
this.toString = toString;
this.empty = empty;
}
function enqueue(element) { this.dataStore.push(element); }
function dequeue() { return this.dataStore.shift(); }
function first() { return this.dataStore[0]; }
function end() { return this.dataStore[this.dataStore.length - 1]; }
function toString() { return this.dataStore.join("\n"); }
function empty() { return this.dataStore.length === 0; }
連續呼叫 .animate() 實際上是同步將動畫函式推入內部佇列,動畫引擎非同步依序取出執行:
$book.animate({ opacity: 0.25 }).animate({ opacity: 0.5 }).animate({ opacity: 1 });
// 實際執行順序:0.25 → 0.5 → 1,各動畫完成後自動 dequeuing 下一幀
jQuery 提供 .queue()/.dequeue() 手動控制佇列,核心邏輯即陣列 push/shift。
<div id="div1" style="width:100px;height:50px;background:red;cursor:pointer;color:#fff;text-align:center;line-height:50px;">點擊</div>
(function($) {
window.$ = $;
})(function() {
var rquickExpr = /^(?:#([\w-]*))$/;
function aQuery(selector) { return new aQuery.fn.init(selector); }
var animation = function() {
var self = {};
var Queue = []; // 內部動畫佇列
// ... 後續實作入隊/出隊/執行邏輯
};
// ... 選擇器、鏈式調用等基礎架構
});
shift() 需重新索引所有元素,時間複雜度 O(n)