Sending data to a Web Worker
Now that we've seen how to send messages back and forth, we can start to actually put these Web Workers to work. In this recipe, we'll see that you can send data to and from a Web Worker.
Getting ready
This recipe assumes you already have a workspace that allows you to create and run ES modules in your browser. If you don't, please see the first two chapters.
How to do it...
- Open your command-line application and navigate to your workspace.
- Create a new folder named
05-03-send-data-to-and-from-web-workers. - Copy or create an
index.htmlthat loads and runs amainfunction frommain.js. - Create a
main.jswith a function namedonMessagethat takes an argumentmessageand logs out thetypeandindexproperties:
// main.js
function onMessage(message) {
const { result, type } = message.data;
console.log('Result for operation (%s): (%s)', type, result);
} - Create a
mainfunction that creates a worker, sets theonMessageproperty, creates an array of random numbers, and...