Sending messages from the main script

Okay! Once you've set up the listener event correctly, you will want to send some tasks to the worker for it to do. This is how to achieve that:

// script.jsconst awesomeworker = new Worker('myworker.js');awesomeworker.addEventListener('message', e => {    console.log(e.data); // data sent by worker});const data = {task: "add", nums: [5, 10, 15, 20]};// lets send this dataawesomeworker.postMessage(data);

Alright. Here, we're giving a task to the worker to add two numbers. Note that we are able to pass objects/arrays to the postMessage method, which is actually used to post/deliver a message to the worker which is spawned.

Objects messaged through postMessage are copied and not referenced. This means that, ...

Get Learn ECMAScript - Second Edition 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.