How to do it...

  1. Open your command-line application and navigate to your workspace.
  2. Create a new folder named 05-02-send-messages-to-and-from-web-workers.
  3. Copy or create an index.html that loads and runs a main function from main.js.
  1. Create a main.js with a function named onMessage that takes an argument message and logs out the type and index properties:
// main.js 
function onMessage(message) { 
  const { type, index } = message.data; 
  console.log('Main recieved a messge (%s) from index: (%s)',  
              type, index); 
}  
  1. Set a  WORKER_COUNT constant:
// main.js 
const WORKER_COUNT = 5; 
  1. Create a main function that creates WORKER_COUNT workers, sets the onMessage property, and posts the index to the worker:
export function main() { for (let index ...

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.