正如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