Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

JavaScript Essentials - Web Workers

Using web workers for parallel execution

Web Workers provide a way to run JavaScript in background threads, allowing you to execute code in parallel without blocking the main thread. This tutorial covers how to use web workers effectively.

Key Points:

  • Web Workers run scripts in background threads.
  • They enable parallel execution and improve performance.
  • Web Workers communicate with the main thread via messages.

Creating a Web Worker

To create a Web Worker, you need to write the worker script in a separate file and use the Worker constructor in the main script to create a new worker.


// worker.js
self.onmessage = function(event) {
    const result = event.data * 2;
    self.postMessage(result);
};
                

// main.js
const worker = new Worker('worker.js');

worker.onmessage = function(event) {
    console.log('Result from worker:', event.data);
};

worker.postMessage(5); // Send data to the worker
                

Communicating with Web Workers

Communication between the main thread and Web Workers is done using the postMessage method to send messages and the onmessage event handler to receive messages.


const worker = new Worker('worker.js');

// Send a message to the worker
worker.postMessage({ type: 'start', payload: 10 });

// Receive messages from the worker
worker.onmessage = function(event) {
    console.log('Message from worker:', event.data);
};
                

Terminating a Web Worker

When you no longer need a Web Worker, you can terminate it using the terminate method to free up resources.


const worker = new Worker('worker.js');

// Terminate the worker
worker.terminate();
                

Error Handling in Web Workers

To handle errors in Web Workers, you can use the onerror event handler.


const worker = new Worker('worker.js');

worker.onerror = function(event) {
    console.error('Error in worker:', event.message);
};
                

Use Case: Intensive Computation

Web Workers are ideal for performing intensive computations that would otherwise block the main thread.


// worker.js
self.onmessage = function(event) {
    const num = event.data;
    let result = 0;
    for (let i = 0; i <= num; i++) {
        result += i;
    }
    self.postMessage(result);
};

// main.js
const worker = new Worker('worker.js');

worker.onmessage = function(event) {
    console.log('Sum from worker:', event.data);
};

worker.postMessage(1000000); // Calculate the sum of numbers from 0 to 1000000
                

Summary

In this tutorial, you learned how to use Web Workers in JavaScript to perform parallel execution. Web Workers enable you to run scripts in background threads, improving the performance and responsiveness of your web applications.