Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
65 views
in Technique[技术] by (71.8m points)

javascript - How to stop js web worker from within?

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?

question from:https://stackoverflow.com/questions/65875453/how-to-stop-js-web-worker-from-within

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...