UI Thread and Web Worker - dcobbley/capstone-e GitHub Wiki

Unblocking the UI Thread with the Web Worker API

For the official MDN documentation on the Web Worker API, go to https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers.

The Worker constructor takes a single argument, which is the URI of a JavaScript file containing a script to execute. The Worker and the UI thread communicate via the postMethod() method (to send) and the onmessage event (to receive). This raises a Message event, which contains a "data" member that holds whatever payload is being transmitted.

When its work has completed, a Worker can use the close() method to close itself; if the UI thread determines that a worker should be terminated early, it can call the Worker's terminate() method to kill it immediately.

Improving Performance by Passing Data Directly

By default, any data passed between the UI thread and a Worker is copied; since we're planning to transfer and backup potentially large volumes of data, this may have considerable overhead.

Fortunately, objects that implement the Transferable interface can be passed by reference without inducing copies. Do note that this is transferring objects, though; once transferred to another thread, the data in question will no longer be accessible from the originating thread.