Messaging with postMessage
Communicate between main thread and worker.
Communicating With Messages
Because the main thread and worker have separate memory, they talk by passing messages. The postMessage method sends data; the message event receives it.
Sending to the Worker
From the main thread, call worker.postMessage(data). The data can be almost any value: numbers, strings, objects, arrays.
const worker = new Worker('worker.js');
worker.postMessage({ task: 'sum', numbers: [1, 2, 3, 4] });All lessons in this course
- Creating a Web Worker
- Messaging with postMessage
- Transferable Objects
- Use Cases and Limitations