Search code examples
javascripthtmlweb-worker

Do I need to terminate / close / delete a web worker when i'm done with it?


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?


Solution

  • 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.