Search code examples
web-worker

What happens if I keep using postMessage() when a web worker is still in use?


I am pretty new to web workers, but one question I have is, given the following scenario:

  1. I spawn a web worker and set the onmessage handler in Worker
  2. Then I use postMessage() in main thread to trigger the Worker's onmessage
  3. I immediately call another postMessage while the last onmessage task is still in progress

Then, I wonder how does the worker handle that?


Solution

  • The messages are saved in queue. Workers have, just like main thread, a message queue - that launches tasks from events (eg. click), setTimeout and postMessage. Here's how it works:

    image description

    The same applies to main thread as well as Node.js for example. It's how javascript works.

    So to your answer - all messages you send to Worker will be processed in the same order you processed them, one by one.

    Here's a jsFiddle as a test that my claim is true. You will see that although all messages are sent at once, they are processed in order.