1

I have a system where I send a large array into the worker, which then uses a library to compress it. Compression takes a long time a makes the worker busy. I'm wondering if further messages sent to the worker will be received while the worker is still busy. Would the messages be lost? Will they queued and eventually processed by the worker as well?

R.J. Dunnill
  • 2,049
  • 3
  • 10
  • 21
Legomite
  • 99
  • 2
  • 7

1 Answers1

1

Yes, once the worker has finished what it's working on currently, it'll be able to process the next message in the queue. Here's an example:

// https://stackoverflow.com/questions/10343913/how-to-create-a-web-worker-from-a-string
// I put in a Stack Snippet for live demonstration
// in a real project, put this in a separate file
const workerFn = () => {
  self.onmessage = () => {
    self.postMessage('Worker message callback just fired');
    // something expensive
    for (let i = 0; i < 2e9; i++) {
    
    }
    self.postMessage('Expensive operation ending');
  };
};
const workerFnStr = `(${workerFn})();`;
const blob = new Blob([workerFnStr], { type: 'text/javascript' });
const worker = new Worker(window.URL.createObjectURL(blob));

worker.onmessage = ({ data }) => console.log(data);

worker.postMessage(null);
worker.postMessage(null);

This is similar to the idea that when an element in the DOM is clicked on, that click will be processed once the current event loop task finishes, even if said task is expensive.

setTimeout(() => {
  window.onclick = () => console.log('click callback running');

  // something expensive
  for (let i = 0; i < 3e9; i++) {
  }

  console.log('Main synchronous task finishing');
}, 500);
Click here *quickly* after running the snippet
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320