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?
Terminating a Worker We can kill a worker's task by using the terminate() function or have it terminate itself by calling the close() function on self.
terminate() The terminate() method of the Worker interface immediately terminates the Worker . This does not offer the worker an opportunity to finish its operations; it is stopped at once.
The only solution would be to override both Worker. terminate() and DedicatedWorkerGlobalScope. close() in order for these to let you know about it.
How many web workers can run concurrently JavaScript? A web worker is a JavaScript program running on a different thread, in parallel with main thread. The browser creates one thread per tab. The main thread can spawn an unlimited number of web workers, until the user's system resources are fully consumed.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With