Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 305
TKoL Avatar asked Mar 29 '18 09:03

TKoL


People also ask

Can a web worker terminate itself?

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.

How do you end a Webworker?

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.

How can you tell if a Webworker has been terminated?

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?

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.


1 Answers

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.

like image 88
T.J. Crowder Avatar answered Oct 20 '22 01:10

T.J. Crowder