Web Workers Advanced in JavaScript
Transfer an ArrayBuffer in JavaScript to a web worker and return a total with a job ID. The sender loses access to the buffer; its byteLength becomes zero.
Run this example once in a fresh browser console. The console shows the printed results.
1const source = `2self.onmessage = event => {3 const values = new Uint32Array(event.data.buffer);4 let total = 0;5 for (const value of values) total += value;6 self.postMessage({ id: event.data.id, total });7};`;8const url = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }));9const worker = new Worker(url);10worker.onmessage = event => {11 console.log('Job ' + event.data.id + ' total:', event.data.total);12 worker.terminate(); URL.revokeObjectURL(url);13};14worker.onerror = event => {15 console.error('Job failed:', event.message);16 worker.terminate(); URL.revokeObjectURL(url);17};18const marks = new Uint32Array([12, 15, 18]);19worker.postMessage({ id: 7, buffer: marks.buffer }, [marks.buffer]);20console.log('Sender bytes after transfer:', marks.byteLength);
Sample Output
Sender bytes after transfer: 0
Transferring detached the sender buffer immediately.
Job 7 total: 45
The later worker reply contains the ID and the sum 12 + 15 + 18.
In this one
- Transfer an ArrayBuffer to a worker
- Understand detached sender memory
- Tag a request with a job ID
- Clean up after a worker reply
How it works
- 1
Create a worker that reads an incoming buffer and totals its values.
- 2
Install message and error handlers.
- 3
Create a Uint32Array of marks.
- 4
Send its buffer both in the message and transfer list.
- 5
Observe zero sender bytes first, then the later reply for job 7 with total 45.
Edge cases
Using transferred memory
The sender loses access to the original buffer contents.
Do not plan to read marks after transfer. Copy deliberately before sending if you need to keep a local copy.
Wrong value format
Uint32Array is for unsigned 32-bit integers.
Choose a data format suited to the values. Decimal or negative data needs a different type or explicit validation.
What's going on
A web worker is a script that runs separately from the page's main work. This advanced example sends a typed array's backing memory to a worker, calculates a total, and matches the reply with a job ID.
A typed array stores numeric values in a specific binary format. Uint32Array uses unsigned 32-bit integers, and its buffer is the underlying block of bytes. Passing that buffer in the transfer list moves ownership to the worker instead of copying its contents. The sender's buffer becomes detached, which means the sender can no longer use it as before. That is why byteLength prints zero immediately after sending.
The worker rebuilds a view over the received buffer, adds the marks, and returns a small result object. The page receives job 7 with total 45 and then releases the worker and temporary URL. This browser-only example needs a page that allows workers to load from temporary file addresses. Transferring is useful for suitable large data, but a three-number demonstration does not prove a speed improvement.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does the second postMessage argument do here?
Pick an answer to check it.
Question 2
Which log appears before the worker reply?
Pick an answer to check it.
Questions people ask
Why is byteLength zero?
The buffer was transferred away and detached on the sender side. The worker now has the data.
Why include id 7?
An ID lets a caller match results to jobs when a real worker handles several requests.
Can I transfer every object?
No. Only supported transferable objects can go in the transfer list. Ordinary objects are usually copied by message passing.