Creating and Terminating a Web Worker
You'll learn how to instantiate a Worker from a separate JavaScript file and properly clean it up when you're done.
What You're Doing
Web Workers run JavaScript in a background thread, but they don't magically appear—you need to create them explicitly. Think of it like hiring a contractor: you bring them in for a specific job, and when the work is done, you formally end the contract.
Creating a Worker
To create a Web Worker, instantiate a Worker object with the path to a separate JavaScript file:
const worker = new Worker('worker.js');
That's it! The browser spawns a new thread and starts running the code in worker.js. The worker file is completely separate from your main script—it must be a standalone .js file, not inline code.
You communicate with the worker through message passing (which you learned exists in the previous lesson):
worker.postMessage({ task: 'process', data: [1, 2, 3] });
worker.onmessage = (event) => {
console.log('Worker said:', event.data);
};
Terminating a Worker
Workers consume resources (memory, CPU), so when you're finished with one, you should terminate it:
worker.terminate();
This immediately kills the worker thread—no cleanup, no goodbye. It's like unplugging a device. The worker gets no chance to finish current work or respond.
Workers can also terminate themselves from inside their own code:
// Inside worker.js
self.close();
When to Terminate
Terminate workers when their job is complete, when the user navigates away from a feature, or when you need to free resources. Don't leave workers running indefinitely if they're idle.
Key Takeaway: Create workers with new Worker('file.js'), terminate them from outside with worker.terminate(), or let them self-terminate with self.close()—always clean up when the work is done.