19

I'm wondering what happens when a user closes the tab which spawned the worker thread, while the thread is still working. Does it halt everything? If so, is there a way to run the thread in the background even when the tab is closed?

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
Vlad
  • 8,038
  • 14
  • 60
  • 92
  • 2
    8 years has passed, so small update. Now we have service workers that can outlive site for some small period of time. It would go away if no new events to handle. But it can outlive tabs. https://www.w3.org/TR/service-workers-1/#service-worker-lifetime https://stackoverflow.com/questions/46281337/what-happens-to-js-serviceworker-when-i-close-the-tab – Bogdan Mart Sep 26 '20 at 11:00

2 Answers2

15

Yes it halts everything, a (dedicated) worker can't outlive its owner. If you use a shared worker, which can have multiple owners, the worker will only stay alive as long as at least one owner is alive. This is the case even if you pass on the entangled MessagePort to another window (i.e. owner of the message port is not the owner of the worker).

So, with shared workers you can "transfer" the ownership by opening a new window that establishes its own connection with the worker (with new SharedWorker(...)) and then close the old window. But one window must always remain open.

bennedich
  • 12,150
  • 6
  • 33
  • 41
3

Take a look here

http://www.whatwg.org/specs/web-apps/current-work/multipage/workers.html#workerglobalscope

I think it is confirming that once the browser goes away, any workers must stop.

Whenever a Document object is discarded, it must be removed from the list of the worker's Documents of each worker whose list contains that Document.

In the case where you have one window using web workers, and you close that window (or tab), the worker goes away.

If you have a case where you have a window, that opens other windows or tabs, the workers can continue. But if you close everything, they all go away.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
  • 1
    Just to clarify, as the discussion is centered around new windows, this should also apply to new page loads. Loading a new pages discards the current document object (web worker goes away), and recreated on new document load. – ElHaix Feb 22 '12 at 15:51