Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

are messages sent via worker.postMessage() queued?

Tags:

web-worker

After creating a worker, I can send messages to it via postMessage. For example:

var worker = new Worker('helper.js');
worker.postMessage({...});

Inside helper.js, the worker needs to add a listener using onmessage = function (event) { ... };

My question is, if one or more messages are sent to the worker while the worker script is still loading, is it guaranteed that the messages get queued and delivered eventually, or is it possible that they may get lost?

like image 403
HRJ Avatar asked Dec 22 '15 05:12

HRJ


People also ask

Can postMessage send objects?

Simply add a custom toString-method on the object. When trying to send an object with postMessage in IE8 and IE9 they will be converted to a string with the toString-method on the object. Since browsers that support sending objects doesn't call toString we can use this to our advantage.

How do I send a message to a Web Worker?

You need to use the postMessage() method in the onmessage event handler in worker. js : // src/worker. js onmessage = e => { const message = e.


1 Answers

Messages will be queued while the worker script is being downloaded and parsed by the browser, but onmessage must be defined synchronously in the worker (at least in Chrome v56).

The following will not fully work:

worker.js:

setTimeout(function() {
  onmessage = function() {
    console.log('received message');
  }
}, 0);

main-script.js:

var worker = new Worker('worker.js');
worker.postMessage('first message'); // this won't go through
setTimeout(function() {
  worker.postMessage('second message'); // this will
}, 1000);

The worker's onmessage function will only fire for the second message.

I've demonstrated this issue in this plunkr: http://embed.plnkr.co/G54gk9Cz6XhZ3E6ZB3Nf/

importScripts does stop execution in the worker until the scripts are downloaded, so waiting until after that to define onmessage should be fine.

like image 186
tobek Avatar answered Oct 07 '22 00:10

tobek