// worker.js
self.onmessage = function(event) {
const result = event.data * 2;
self.postMessage(result);
};
// main.js
const worker = new Worker('worker.js');
worker.onmessage = function(event) {
console.log('Worker result:', event.data);
};
worker.postMessage(10); // Send data to the worker
In this example, the worker.js
file defines a simple worker that doubles the input value. The main script creates the worker, sends a value to it, and handles the result when the worker responds.