Terminating a Worker
You'll learn how to properly stop a worker's execution, both from the main thread and from within the worker itself.
When you're done with a Web Worker—whether it's finished its job or you simply don't need it anymore—you should explicitly terminate it to free up system resources. Leaving workers running unnecessarily wastes memory and CPU.
Two Ways to Stop a Worker
From the Main Thread: terminate()
The main thread can forcibly stop a worker at any time by calling terminate() on the worker object:
const worker = new Worker('task.js');
// Later, when you're done:
worker.terminate();
This is an immediate, hard stop. The worker's script stops executing instantly, mid-operation if necessary. It won't finish any current task or clean up state. Think of it like pulling the plug on a device—no graceful shutdown.
From Inside the Worker: close()
A worker can terminate itself by calling close() from within its own script:
// Inside task.js (the worker)
self.addEventListener('message', (e) => {
if (e.data === 'finish') {
console.log('Worker shutting down');
self.close(); // Worker terminates itself
}
});
This is slightly more graceful—the worker decides when to stop, potentially after finishing its current task.
When to Terminate
Terminate workers when they're no longer needed to avoid memory leaks. If you create workers dynamically (like one per user action), make sure to clean them up afterward.
Key Takeaway: Use worker.terminate() from the main thread for immediate shutdown, or self.close() inside the worker for self-termination—both free up resources and prevent memory leaks.