CodeBlanks Logo Icon CodeBlanks

Challenge - Worker architecture

JavaScript course · Expert · Lesson 60/63

Run a heavy computation in a background thread with Web Workers and transferable objects.

Background computation with a worker

In this challenge you will run a heavy computation in a background thread with a Web Worker. First you create a worker with new Worker('worker.js').

To send data from the main thread you call worker.postMessage(data); when sending a transferable object you pass [buffer] as the second argument and the buffer is moved instead of copied.

You receive the worker's reply with worker.onmessage; event.data holds the value the worker sent.

Exercise Background computation with a worker

Create a Worker with new Worker('worker.js'). Then assign a handler to worker.onmessage and read the incoming value via event.data. Finally call worker.postMessage(data, [buffer]): the first argument is the data, the second is the list of buffers to transfer.

Show example solution
1 }, [buffer]);.

Example solution:
const worker = new Worker('worker.js');

worker.onmessage = function(event) {
  console.log(event.data);
};

const buffer = new ArrayBuffer(8);
worker.postMessage({ payload: 1 }, [buffer]);

Test yourself

  1. What does the transfer list in postMessage do?

    worker.postMessage(data, [buffer]);
    • It compresses the data
    • It moves the buffer without copying
    • It delays the message
    • It restarts the worker
    Show answer

    It moves the buffer without copying — Correct! The transfer list moves the buffer without copying; this saves time and memory for large data.

  2. Complete the onmessage assignment

    const worker = new Worker('worker.js');
    worker.____ = function(event) {
      console.log(event.data);
    };
    Show answer
    const worker = new Worker('worker.js');
    worker.onmessage = function(event) {
      console.log(event.data);
    };
  3. Match the worker concepts

    new Worker(url)
    Create worker
    postMessage(data)
    Send data
    onmessage
    Catch message
    event.data
    Incoming result

All lessons in Expert