简体   繁体   English

网络工作者 postMessage 处理顺序

[英]web worker postMessage process order

With the following code:使用以下代码:

HTML FILE: HTML文件:

<!DOCTYPE html>

<html>

    <head>
        <title></title>
        <!--<script type="text/javascript" src="worker.js"></script>-->
        <script type="text/javascript" src="run.js"></script>
    </head>

    <body>
        <div id='log'></div>
    </body>

</html>

run.js:运行.js:

window.onload = function(){

    var worker = new Worker('worker.js');

    var log = document.getElementById('log');

    log.innerHTML += "<p>"+"test"+"</p>";

    worker.addEventListener('message', function(e) {
        //alert(e.data);
        log.innerHTML += '<p>' + e.data + '</p>';
    }, false);

    for(var i=1; i<21;i++){
        worker.postMessage(i);
    }
};

worker.js工人.js

self.addEventListener('message', function(e) {
  self.postMessage(e.data);
}, false);

the output is as I would expect a list of 1 to 20, but if I uncomment the alert call in the run.js message listener it prints out 20 to 1 instead.输出与我期望的 1 到 20 的列表一样,但是如果我取消注释 run.js 消息侦听器中的警报调用,它会打印出 20 到 1。 Is this because of the alert causing the delay in writing to the page and the message processing is backed up in a stack so the last one on is the first one off?这是因为警报导致写入页面的延迟,并且消息处理在堆栈中备份,所以最后一个打开是第一个关闭? or is it something else.或者是别的什么。

Yes this is because of "alert()".是的,这是因为“警报()”。 It blocks the further execution of the code inside the block of the worker listener.它阻止了工作侦听器块内代码的进一步执行。 By other words, the code:换句话说,代码:

log.innerHTML += '<p>' + e.data + '</p>';

is executed only after the "OK" button on the modal window of the alert box is pressed, in wich order you will press them, in this order the "log.innerHTML" will be changed, so you press them in descending order and that's why you get this result.仅在按下警报框模态窗口上的“确定”按钮后执行,按顺序按下它们,按此顺序更改“log.innerHTML”,因此您按降序按下它们,就是为什么你得到这个结果。 If you don't use alert messages everything goes well.如果您不使用警报消息,一切都会顺利。

I think this was a bug in Firefox.我认为这是 Firefox 中的一个错误。 I'm not seeing this behavior in 2020 in any browser I tried: they all order from 1 to 20.我在 2020 年尝试过的任何浏览器中都没有看到这种行为:它们的顺序都是从 1 到 20。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM