JavaScript Web Worker - close() vs terminate()

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.


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


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