JavaScript Web Worker - close() vs terminate()

巧了我就是萌 提交于 2021-02-17 21:11:11

问题


I'm not totally understanding the difference between the close() vs terminate() methods for Web Workers. I've read the descriptions here and it seems to be doing the same thing?? http://www.w3.org/TR/workers/

When would I use one over the other?


回答1:


The close() method is visible inside the worker's scope. The terminate() method is a part of the worker object's interface and can be called "from the outside".

If you create a worker in your main script and want to stop it from that script you should call the terminate() on the worker object. If you want to stop the worker from the worker code (for example as a response to an external message) you should call the close() method.

Source: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Terminating_a_worker




回答2:


Indeed the close() function is visible from inside the scope of the Worker.

terminate() is visible from outside (i.e: the script that calls the worker can shut it down using this function)

TBH this is a little bit confusing at first, but once you implemented you will get used to it




回答3:


I found a good use case for self.close() over terminate. Inside my web worker I had a setInterval function that was receiving and posting back an objects position. Using terminate kills the web worker for good, so I could not send the play message back to the worker. Meanwhile closing it, allowed me re open it and restart the timer.




回答4:


Other differences when you use web worker in React:

  1. if you use terminate, you just call the api, and it is synchronous
  2. if you use close, you need to call postMessage and send a signal/message so that the worker can kill itself inside its scope. postMessage is NOT synchronous, as far as I know.

The problem of close is that if want to kill the worker when you unmount a component, you need to do it synchronously, otherwise, you may get a warning, especially when you try to clean up things in the ComponentWillUnmount lifecycle hook or useEffect hook (otherwise, there will be multiple zombie web worker instances alive).

The warning looks like:

Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

OR:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.



来源:https://stackoverflow.com/questions/30500883/javascript-web-worker-close-vs-terminate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!