DIV CSS 佈局教程網

自己動手寫一個 JavaScript 事件佇列
編輯:關於JavaScript     

前陣子在網上看到一系列〈寫一個 JavaScript 異步調用框架〉的文章。異步操作最大的困擾是觸發順序不可控,而這問題我以前也遇到過,當時的解法很土——直接在 ajax 回呼裡巢狀下一個事件。

那系列文章寫得不容易讀,加上基礎與大局觀都不足,看得很吃力,也不太喜歡它的呼叫方式。理想的 API 應該長這樣:

var chain = Async.go(0);
chain
.next(function(){ setTimeout("alert(1)", 3000) })
.next(function(){ setTimeout("alert(2)", 3000) })
.next(function(){ setTimeout("alert(3)", 3000) });

但實際上如果是異步調用,卻得這樣寫:

var chain = Async.go(0);
chain.next(function(){
var operation = new Async.Operation();
setTimeout(function(){ operation.yield("hello"); }, 3000);
return operation;
});

最後一篇提到再包裝一層就能改善,我想大致可以解決這種不順手。而這個念頭其實我早就有了,只是當時在群裡問有沒有這種「能照我的順序觸發」的類別時,得到的回應多半是「在 onreadystatechange 裡執行就好啦」,甚至被笑,加上自己還是初學的菜鳥,就擱下了。如今雖然仍是菜鳥,總歸飛了一段路,試著照自己的理解寫一個看看。

程式碼

/**
* KEQueue —— Events Queue
* @param data 事件佇列中每個事件都會把該參數作為第一個參數傳遞下去,
*             除非透過 KEQueue.status 修改它的值。
* @method next(Function)  下一個要執行的事件
* @method wait(Number)    等待一段時間後執行下一個事件
* @method sleep()         停止事件序列的執行
* @method wake()          繼續執行事件序列
**/
var KEQueue = function(data) {
this.staticQueue = [];     // 同步方法佇列
this.asyncQueue  = [];     // 異步方法佇列
this.status = "running";
this.result = data;
return this;
}

KEQueue.prototype = {
next: function(callback, async) {
if (!!async) {
this.staticQueue.push("async");   // 用字串當「這裡有異步方法」的標記
this.asyncQueue.push(callback);
} else {
this.staticQueue.push(callback);
}
return this;
},
wait: function(delay) {            // 延遲執行
var self = this;
this.next(function() {
setTimeout(function(){ self.wake.call(self); }, delay);
}, true);
return this;
},
go: function() {
if (this.staticQueue.length == 0) return;
while (this.staticQueue.length > 0) {
if (this.status === "sleep") return;
var fun = this.staticQueue.shift();
if (typeof fun == "string" && fun == "async") {
fun = this.asyncQueue.shift();
fun(this.result);
this.sleep();                    // 異步方法執行後主動休眠
} else {
fun(this.result);
}
}
},
sleep: function(){ this.status = "sleep"; },
wake:  function(){ this.status = "running"; this.go(); }
}

思路其實很簡單:循環執行一個陣列裡的方法,遇到不是 function 的項目(也就是那個 "async" 標記)就停止,直到被 wake() 叫醒。

使用範例

function show(n){ console.log(n); }

// 範例一:加入事件並依序執行
var o = new KEQueue("0");
o.next(function(d) {              // 參數是建構時傳入的資料
show(d + 1);
}).next(function(d) {
setTimeout(function() {           // 模擬延時(異步)操作
show(d + 2);
o.result = 0;                   // 可修改傳遞的資料
o.wake();                       // 需手動喚醒
}, 2000);
}, true).next(function(d){
show(d + 3);
}).go();

o.next(function(d) {
setTimeout(function(){ show(d + 4); o.wake(); }, 1000);
}, true).wait(1000)               // 手動推遲 1 秒
.next(function(d){ show(d + 5); }).go();

// 範例二:執行途中動態加入事件
o.next(function(){ show(1); })
setTimeout(function() {
o.next(function(){
setTimeout(function(){ show(2); o.wake(); }, 2000)
}, true).go();
}, 1000);
setTimeout(function() {
o.next(function(){ show(3); }).go();
}, 2000);

顯然,僅僅「照我加入的順序執行」並不等於完整解決異步問題。如果每個事件都很耗時,就得全部當異步處理,那這個佇列只剩下「幫你梳理順序」的價值。

晚間睡前想到這點有點洩氣,但早上通勤時突然想起:JavaScript 是單執行緒的,事件會被序列化處理;若是多執行緒環境,大概根本不需要做這種佇列。剛才寫了個 demo 試過,看來還是不會出問題。

如果你有建議或指教,歡迎留言。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved