10

I have an app which uses a web worker to clean up an indexedDB database. I have it set up so it can be initiated from a global function call, and if that function is called again before it's done, it does not restart, but if the function is called after it's done it does restart, by creating a new instance of the worker. This aspect of it all works just fine for me.

Do I need to delete, destroy, terminate the old instance of the worker in any sense after it's finished working?

3
  • It always make sense to close any connections. Often it is one line in your code so it doesn't make much extra work Mar 29, 2018 at 9:35
  • A web worker do not affect the performance of the page, so it just a mater of preference Mar 29, 2018 at 9:36
  • @AbdeslemCharif: It certainly can affect the performance of the page, like any other process, if it loads the CPU. Mar 29, 2018 at 9:37

1 Answer 1

12

Do I need to delete, destroy, terminate the old instance of the worker in any sense after it's finished working?

In the normal case, a worker registers an event handler to listen for messages from the main script, and so yes, you need to tell it to unregister that if you want the worker to be unloaded. You can do that in one of two ways:

  1. Send it a message telling it to clean up, and have the worker respond to that message by unregistering all event handlers. This lets the worker exit gracefully.
  2. Use Worker#terminate, which terminates the worker immediately without giving it any chance to finish what it's doing.

If the worker isn't listening for messages, doesn't have other event handlers registered, and isn't doing work in a loop, you don't have to do anything specific (but the odds of that are low, workers almost always register event handlers for listening to messages).

...but if the function is called after it's done it does restart, by creating a new instance of the worker.

I recommend revisiting that design. Instead, create the worker once, and then send it a message each time you need it to do something, rather than creating the whole thing again each time.

3
  • At the moment, my design doesn't involve the web worker listening to any messages - it starts its work without a self.onmessage type listener, as soon as it's instantiated.
    – TKoL
    Mar 29, 2018 at 9:46
  • @TKoL: Do you keep a reference to it (or keep one until it sends you a message saying its down, then release it)? I think if it doesn't register any handlers (or it then unregisters them), finishes its work, and you don't have a reference to it, it gets cleaned up automatically. Mar 29, 2018 at 9:55
  • Oh alright, that sounds perfect then. Thanks my guy
    – TKoL
    Mar 29, 2018 at 10:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.