Reputation: 1387
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?
Upvotes: 40
Views: 32875
Reputation: 578
hmm, simply.
// immediately terminate the main JS file
worker.terminate();
// stop the worker from the worker code.
self.close();
Upvotes: 2
Reputation: 462
Other differences when you use web worker in React:
terminate
, you just call the api, and it is synchronous
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.
Upvotes: 5
Reputation: 161
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.
Upvotes: 2
Reputation: 445
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
Upvotes: 1
Reputation: 3643
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.
Upvotes: 77