正如Jakub指出的那樣,異步事件處理是JavaScript的優點之一。我建議重新考慮你的應用程序流程來支持這一點,而不是試圖序列化它。此外,你並沒有承諾事件觸發的順序是你期望他們觸發的順序。拖動多個書籤可以按任意順序生成事件。
如果您確實需要確保您的程序按照它們進來的順序處理事物,並且一次只處理一個項目,則可以將您的邏輯分爲兩部分:eventHandler
本身可以是填充您需要以某種方式處理事件隊列,並且可以在超時驅動循環中運行另一個函數,檢查隊列,關閉項目並對其進行處理。類似於以下(未經測試)代碼:
function SerializedEventHandler() {
chrome.bookmarks.onCreated.addListener(this.enqueue.bind(this));
}
SerializedEventHandler.prototype = {
queue_: [],
timer_: null,
enqueue: function (e) {
this.queue_.push(e);
this.startProcessing();
},
startProcessing: function() {
if (!this.timer_)
this.timer_ = setTimeout(this.process.bind(this), 100);
},
process: function() {
if (this.queue_.length) {
var item = this.queue_.shift();
// do something with `item`
this.timer_ = clearTimeout(this.timer_);
this.startProcessing();
}
}
};
這有道理嗎?
我不認爲這是工作 – anp 2011-04-10 11:59:20
@anp爲什麼呢? – 2011-04-10 12:30:09
即使有延遲,輸出也是一樣的 – anp 2011-04-11 02:49:51