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.html
that loads and runs amain
function frommain.js
. - Create a
main.js
with a function namedonMessage
that takes an argumentmessage
and logs out thetype
andindex
properties:
// main.js function onMessage(message) { const { result, type } = message.data; console.log('Result for operation (%s): (%s)', type, result); }
- Create a
main
function that creates a worker, sets theonMessage
property, creates an array of random numbers, and...