Search code examples
javascriptweb-worker

web worker postMessage process order


With the following code:

HTML FILE:

<!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:

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

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. 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.


Solution

  • 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. If you don't use alert messages everything goes well.