简体   繁体   中英

Detecting Close/Terminate within WebWorker

From the documentation Worker , calling the terminate method on the worker terminates the web worker. Is there a way to detect the terminate call on the Worker side?

I tried overriding the terminate and close methods on self but it doesn't seem to be called.

self.terminate = function() { ... }
self.close = function() { ... }

Given that worker.terminate() from the outside even stops the running script that is on the stack, there is no way you'd be able to react to anything from there, since even if there were an event, your script would be dead before it fires.

self.close() however does let the current script run until completion, so there you could imagine a "beforeterminated" event, but it's hard to see why you couldn't simply call the callback yourself when calling this method.

Of course you could overwrite the worker.terminate() method so that it sends a simple message on your Worker and let your Worker close itself on the other side, but that wouldn't do the same since you would need to wait for the JS stack to be empty before being able to treat that message. So the best is probably to NOT overwrite this method but have in your communication API one method that'd let the Worker know it should close itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM