Middle
How to create a Web Worker thread in JavaScript?
sobes.tech AI
Answer from AI
Creating a Web Worker thread in JavaScript can be done using the Worker constructor.
// Create a new Web Worker by passing the path to the JS file,
// which will run in a separate thread.
const worker = new Worker('worker.js');
In the worker.js file (or any other specified when creating the worker), the code will execute in a separate thread.
// worker.js
// Handling messages sent from the main thread
self.onmessage = function(event) {
const receivedData = event.data;
console.log('Message received from main thread:', receivedData);
// Sending a message back to the main thread
const responseData = { message: 'Hello from Worker!', data: receivedData };
self.postMessage(responseData);
};
// Optionally, add error handling
self.onerror = function(error) {
console.error('Error in Worker:', error);
};
In the main thread (where the worker was created), you can interact with the worker:
// main.js
const worker = new Worker('worker.js');
// Sending a message to the Web Worker
worker.postMessage({ command: 'start', payload: 'some data' });
// Handling messages received from the Web Worker
worker.onmessage = function(event) {
const receivedData = event.data;
console.log('Message received from Worker:', receivedData);
};
// Handling errors in the Web Worker
worker.onerror = function(error) {
console.error('Worker error in main thread:', error);
};
// Terminating the Web Worker (optional)
// worker.terminate();
Key points:
- Communication: Data exchange between the main thread and the worker occurs via messages using
postMessage()and theonmessagehandler. - Restrictions: Workers do not have access to the DOM, the
windowobject, or other global browser objects. They have limited access tonavigator,location,XMLHttpRequest,setTimeout,setInterval,fetch,WebSockets, and others. - Isolation: The code in the worker runs in a separate thread, preventing blocking of the main thread and improving performance, especially when performing resource-intensive computations.