Search code examples
javascriptmultithreadingweb-worker

About Web Workers parallelism


My JS code of the main thread:

$('body').on('click',function(){alert('click');});
var worker = new Worker('worker.js');
worker.addEventListener('message', function(e) {    
        console.log(e.data);
});

and the code inside worker.js

var n = 1;
while (true) {
  n++;
  postMessage(n);
}

I 've just started to study about Web workers. They are supposed to not block UI and let you interact with it, while they (the workers) run in a separate thread as to implement parallelism. In practice, what am I getting by running the above code is a stuck browser with no response to any click. The worker works by outputting numbers, however where is parallelism and independence of UI?

I am awaiting for some good explanation.

Thank you


Solution

  • You are flooding the main thread with messages sent from the worker via postMessage(). They are probably arriving faster than it can dispatch them and log them, thus leaving no other time for the main thread to do much. Change your postMessage calls so it only sends an update to the main thread when 500ms have elapsed and you will not be overloading the main thread, allowing it do other things in between messages.

    For example, try this in worker.js:

    var n = 1;
    var lastSend = Date.now();
    var now;
    while (true) {
      n++;
      now = Date.now();
      if (now - lastSend > 500) {
          lastSend = now;
          postMessage(n);
      }
    }
    

    And, this will only do a postMessage of the lastest count every 500ms to keep from overloading the main thread trying to process all those messages.

    For the worker to run independently from the main thread, it needs to actually be independent from the main thread, performing independent work, not trying to communicate with it all the time. It is best used for compute intensive operations that are mostly independent of the main thread and only occasionally need to communicate with the main thread.