0Pricing
JavaScript Academy · Lesson

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

  1. Creating a Web Worker
  2. Messaging with postMessage
  3. Transferable Objects
  4. Use Cases and Limitations
← Back to JavaScript Academy