window.postMessage 保证事件的顺序吗?
window.onmessage = ...
window.postMessage('1', '*');
window.postMessage('2', '*');
是否 postMessage
(http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#queue-a-task)保证事件的顺序?
window.onmessage = ...
window.postMessage('1', '*');
window.postMessage('2', '*');
Does postMessage
(http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#queue-a-task) guarantee the order of events?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道,尽管 规范似乎表明它没有做出这样的保证(这令人惊讶)。很明显,一旦将
MessageEvent
添加到接收端的任务队列
中,尽管MessageEvent
创建和分派,它的顺序仍会保持不变。与原始postMessage
调用异步,因此理论上您可能会出现以下情况:主线程:
如果线程管理系统允许第二个
postMessage
在第一个线程设法分派MessageEvent
,并且由于任何不幸的原因允许较新的线程执行(稀释的优先级反转),再次在第一个设法分派之前,那么您确实会以相反的顺序收到这些消息。尽管规范中可能有其他地方为这些异步执行提供了更多上下文并排除了这种情况 - 但我找不到它。
I don't know, although the wording of the spec seems to suggest it doesn't make such guarantees (which is surprising). It's clear that once the
MessageEvent
is added to thetask queue
on the receiving end, then it's order is maintained, although theMessageEvent
creation and dispatch are asynchronous to the originalpostMessage
call, so theoretically it appears that you could have the following situation:main thread:
If the thread management system allowed the second
postMessage
to execute before the first thread managed to dispatch theMessageEvent
, and for whatever unlucky reason allowed that newer thread to execute (a diluted priority inversion), again before the first managed to dispatch, then you would indeed receive those messages in the reverse order.Although there might be some other place in the spec that provides more context for these asynchronous executions and rules out this case - I couldn't find it.
window.postMessage()
仅在被调用时触发消息事件,并且与经典事件发布-订阅机制一样,不能真正保证其顺序。window.postMessage()
only triggers a message event on being invoked, and as with classic event publish-subscribe mechanism, there is not real guarantee of the order in their order.