Search code examples
javascriptweb-worker

What happens when a web worker class gets garbage collected


I have a class which handles the creation of a new web worker when the class is instantiated, post a message to the worker that returns a promise that gets resolved when the worker is done with the task. Basically, I am calling a class which handles creating, posting, listening and terminating the worker.

However, if I create a new instance of this class, post a message, and end my function, what happens to the worker? Does it become orphaned and keeps running its task until it's done?

Also, this is a bit tangential, but how bad would it be to instantiate n number of workers at once? 8? 20? 50? How does the browser handle that?


Solution

  • Does it become orphaned and keeps running its task until it's done?

    Yes. Per the spec, in this instance the event loop must run to completion, the worker gets marked as "suspendable" and finally, the

    Reference Step 10

    how bad would it be to instantiate n number of workers at once? 8? 20? 50?

    You can play here: http://math.hws.edu/eck/jsdemo/jsMandelbrot.html

    I have personally seen 16 worker apps humming along. There is a trade off with spinup/teardown and messaging that must be considered.