Summary - Web Workers
Build an app that sorts a large array in the background with a worker.
Summary - Web Workers
In this group you learned to create a worker, exchange messages, receive replies and transfer large data. Now we will combine everything into an app that sorts an array in the background.
The flow: the main thread sends a large array of numbers to the worker; the worker sorts it and sends the result back; the main thread catches it with onmessage. For large data, we use an ArrayBuffer to skip the copy cost.
Exercise Start the sorter worker and send an array
Create a worker from 'sorter.js'. Then send { numbers: [9, 3, 7] } with worker.postMessage.
Show example solution
const worker = new Worker('sorter.js');
worker.postMessage({ numbers: [9, 3, 7] });
Exercise Transfer a large buffer
Create an ArrayBuffer named buffer of 1024 bytes. Then send it with ownership transferred via worker.postMessage(buffer, [buffer]).
Show example solution
const buffer = new ArrayBuffer(1024);
worker.postMessage(buffer, [buffer]);
Test yourself
-
What is the flow in a sorting worker?
- The worker fetches the data, then sorts it
- The main thread sorts, the worker displays it
- The main thread sends, the worker sorts and replies
- The worker writes to a file, the main thread reads it
Show answer
The main thread sends, the worker sorts and replies — Correct! The main thread sends, the worker sorts and replies.
-
Catch the result
worker.____ = function(event) { console.log(event.data); };Show answer
worker.onmessage = function(event) { console.log(event.data); };