Middle
Как остановить и уничтожить объект web worker?
sobes.tech AI
Answer from AI
It can be stopped by calling the terminate() method on the worker instance. This will immediately end its execution without waiting for the current tasks to finish.
The web worker object is automatically destroyed by the JavaScript garbage collector once there are no more references to it and its resources are released.
Example of stopping:
// Creating a worker
const myWorker = new Worker('worker.js');
// Adding a message handler (optional)
myWorker.onmessage = function(event) {
console.log('Received from worker:', event.data);
};
// Sending a message (optional)
myWorker.postMessage('Hello Worker!');
// Stopping the worker
myWorker.terminate();
It is important to remember that after calling terminate(), the worker stops responding to any messages and cannot be restarted. To perform a new task, a new Worker instance must be created.