How it works...

Constructing the worker with the name of the worker file creates a worker on a new thread. By setting the onmessage event listener on the global context of the worker, we are able to receive messages from the main thread.

After creating the worker, the main function can use that reference to post messages to the new worker. The argument of the postMessage method is passed to the worker as the data attribute of the message property that is received.

Get ECMAScript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.