Main Thread
Main Thread
Section titled “Main Thread”Introduction
Section titled “Introduction”The main thread creates workers, sends them data, and receives results via postMessage() and onmessage.
Creating a Worker
Section titled “Creating a Worker”// Create a worker from a separate JS fileconst worker = new Worker('worker.js');
// Send data to workerworker.postMessage({ numbers: [1, 2, 3, 4, 5] });
// Receive results from workerworker.onmessage = (event) => { console.log('Result from worker:', event.data);};
// Handle errorsworker.onerror = (error) => { console.error('Worker error:', error.message);};Visual Explanation
Section titled “Visual Explanation”flowchart LR subgraph "Main Thread" A["UI Updates"] B["User Events"] C["DOM Manipulation"] end
subgraph "Worker Thread" D["Heavy Computation"] E["Data Processing"] F["File Parsing"] end
Main -->|"postMessage()"| Worker Worker -->|"postMessage()"| Main
style Worker fill:#4CAF50 style Main fill:#2196F3Terminating a Worker
Section titled “Terminating a Worker”// Stop the workerworker.terminate();
// After termination, the worker can no longer be usedSummary
Section titled “Summary”- Create with
new Worker('file.js') - Send data with
worker.postMessage(data) - Receive with
worker.onmessage = (e) => {} - Terminate with
worker.terminate()