1

TLDR: What is an alternative to WorkerGlobalScope.close() which is not deprecated

I want to close/stop/terminate a Javascript web worker from the inside, after its job is done, since there is a setInterval() which keeps being active even after the main work is done.

Reading this SO question (JavaScript Web Worker - close() vs terminate()), it seems like self.close() is what I'm searching for. But apparently this is deprecated (stated here) without any mention of alternatives.

The only alternative I have come up with so far would be to send a message to the main thread which then invokes a worker.terminate() call, but that seems like overkill since I would then need to check every message that comes this way for a termination request.

Am I missing something? What should I use?

bjrne
  • 355
  • 5
  • 14
  • 2
    You could use `setTimeout()` instead of `setInterval()` and when it's time to stop simply do not initiate the next timer call. – Pointy Jan 24 '21 at 20:15
  • Interesting workaround, thx for the idea, however not really what I had in mind :D – bjrne Jan 24 '21 at 20:17
  • Can just kill the `setInterval` with `clearInterval`? – zfj3ub94rf576hc4eegm Jan 24 '21 at 22:28
  • Thanks, it solves a part of the problem, like the answer of Pointy. However I would still prefer a solution to stop all the worker reliably at any time and also halfway through the script. Also I'd like to not worry about all functions & intervals I need to stop. – bjrne Jan 24 '21 at 22:59

1 Answers1

2

This notice is misleading .close() is not deprecated at all.

What happens here is that in the specs WorkerGlobalScope is an interface that is used by different worker types (DedicatedWorkers, ServiceWorkers, SharedWorkers, and maybe other Worklets in other specs).
All these types don't have a .close method (e.g ServiceWorkers don't), and thus this method has been moved to each specific types of worker global scope's definition.

For instance you can see that for the DedicatedWorkerGlobalScope, it's still here, and isn't scheduled to be deprecated any time soon.

And it's actually also there in MDN.

Kaiido
  • 123,334
  • 13
  • 219
  • 285