Reputation: 518
I've read in many places (including here, in Stack Overflow) that web workers can be killed and restarted by the browser at any time. Well, probably "at any time" means "as long as they are doing something", but the thing is that they can be killed and restarted by the browser without prior warning, losing any data stored in globalThis
.
But for the life of me I cannot find that in the specification, and it worries me because I'm actually using a Web Worker whose proper functioning relies in keeping some info data in a global variable to keep minimal state between calls of the message handling function.
This web worker works like a charm, and state is kept unless of course the page is refreshed, but I'm afraid that the app can fail if the browser decides to restart the web worker, and for sure it will if that happens.
I've googled about this, specially looking for examples and alternatives for rewriting my web worker without the need for that global state, but I haven't found anything relevant.
Can anyone point me to some official information about this?
Upvotes: 2
Views: 326
Reputation: 136707
I've read in many places (including here, in Stack Overflow) that web workers can be killed and restarted by the browser at any time.
Nope, they won't ever restart your (dedicated) Worker in any way.
The browser can kill a Worker if
Worker#terminate()
method has been called.DedicatedWorkerGlobalScope#close()
method has been called, and the current task is completed.MessagePort
or inner Worker
objects susceptible of receiving messages from the outside.So as long as you keep a reference to your Worker
object in your main thread, and don't call yourself one of the closing methods, there is no way the Worker can be killed by the browser.
Note: The rules for SharedWorkers, ServiceWorkers, and other Worklets are all different, this answer treats only Dedicated Workers, created from new Worker()
.
Upvotes: 5