# Web Workers

Web Workers provide a simple means for web content to run scripts in background threads. The worker thread can perform tasks without interfering with the user interface.

## 1. The Problem: Single-Threaded JavaScript

JavaScript runs on a single thread (the main thread). If you execute a computationally expensive task (like processing a huge image or sorting a massive array) on the main thread, the UI freezes. The user cannot click buttons, scroll, or interact with the page until the task finishes.

## 2. The Solution: Background Threads

Web Workers allow you to offload these heavy tasks to a separate thread.
*   **Main Thread:** Handles UI, DOM manipulation, and user events.
*   **Worker Thread:** Handles heavy calculations, data processing, etc.

## 3. Creating a Worker

A worker is created by passing a script file to the `Worker` constructor.

**main.js**
```javascript
if (window.Worker) {
  const myWorker = new Worker("worker.js");

  // Send data to the worker
  myWorker.postMessage([10, 20]);
  console.log('Message posted to worker');

  // Receive data from the worker
  myWorker.onmessage = function(e) {
    console.log('Message received from worker', e.data);
  };
}
```

**worker.js**
```javascript
onmessage = function(e) {
  console.log('Worker: Message received from main script');
  
  const result = e.data[0] * e.data[1];
  
  if (isNaN(result)) {
    postMessage('Please write two numbers');
  } else {
    const workerResult = 'Result: ' + result;
    console.log('Worker: Posting message back to main script');
    postMessage(workerResult);
  }
}
```

## 4. Communication

Communication between the main thread and the worker happens via **message passing**.
*   `postMessage(data)`: Sends data.
*   `onmessage`: Event handler for receiving data.

**Note:** Data passed between the main thread and workers is **copied**, not shared. Objects are serialized (using the structured clone algorithm) and deserialized on the other end.

## 5. Limitations

Workers run in a different global context than the current window.
*   **No DOM Access:** Workers cannot access `document`, `window`, or `parent`. You cannot manipulate the UI directly from a worker.
*   **Limited Scope:** They can access `navigator`, `location` (read-only), `XMLHttpRequest`, `fetch`, `setTimeout`, and `setInterval`.

## 6. Terminating a Worker

If a worker is no longer needed, you can terminate it to free up resources.

```javascript
myWorker.terminate();
```

[[programming/javascript/vanilla/javascript]]
[[programming/javascript/vanilla/event-loop]]
[[programming/javascript/vanilla/shared-array-buffer-and-atomics]]