Workers in JavaScript

Introduction

JavaScript, often celebrated for its simplicity, surprises many with its single-threaded nature, seemingly limiting its ability to handle complex tasks efficiently. However, it has a hidden concurrency solutions. What are those solutions? Answer is - Web workers.

What are web workers?

Web workers are a JavaScript feature introduced to allow web applications to execute scripts in background threads. Traditionally, JavaScript runs in a single thread, which means that heavy computational tasks or operations such as parsing large data sets can cause the user interface to become unresponsive. Web workers address this issue by enabling the execution of scripts in parallel threads, separate from the main execution thread.

How web workers work ?

Take the example of simple 2 buttons:
This HTML template includes two buttons: one for calculating the sum of numbers and another for changing the background color.
The JavaScript code is in script.js file provided in the <script> tag handles the button click events.

script.js:

Scenario:
User click the sumButton then click bgButton

Problem:

  • The operation initiated by clicking the sumButton may be time-consuming due to the extensive loop it executes.

  • If the sumButton is clicked before the bgButton, the background change triggered by the bgButton could be delayed or impeded until the sumButton operation completes.

  • This sequence of events has the potential to diminish the responsiveness of the user experience, particularly if the calculation process takes a noticeable amount of time.

Solution:

  • Create a worker thread:
    Create a worker.js file, set the onmessage event handler to listen for messages from the main thread.

  • Worker thread processing in background:
    When a message is received, it starts processing it in the background and creates a parallel processing

  • Send the result back once processed:
    Inside the onmessage event handler in worker.js, the postMessage method is used to send the result (sum) back to the main thread.

How will main thread receive the message from worker thread worker.js ?

  1. Line 1: Create a worker

  2. worker.onmessage will receive the message from worker thread.

Flow between main thread and worker thread

Here's a simplified representation:

Creating an actual picture of the flow visually:

  1. Script File (main.js):

    • Sends a message using postMessage.

    • Waits for a response from the worker using an event listener (onmessage).

  2. Worker File (worker.js):

    • Listens for messages from the main script using onmessage.

    • Processes the message.

    • Sends a response back to the main script using postMessage.

  3. Script File (main.js):

    • Receives the processed message from the worker using onmessage.

Use cases

  1. Parallel Processing: Web workers enable parallel processing of tasks such as data parsing, image processing, or mathematical calculations, improving overall performance and responsiveness.

  2. Background Tasks: Tasks that don't require direct interaction with the DOM, such as logging, analytics, or sending asynchronous requests, can be offloaded to web workers, freeing up the main thread for user interactions.

  3. Real-Time Data Processing: Web workers are ideal for handling real-time data streams or continuous updates, ensuring smooth user experiences while processing large datasets or performing complex computations in the background.

When not to use web workers

  1. Simple Tasks: For simple tasks that execute quickly and don't significantly impact the user interface, introducing web workers may add unnecessary complexity to the codebase.

  2. Small-Scale Applications: In smaller web applications with limited computational requirements, the overhead of setting up and managing web workers may outweigh the performance gains.

  3. Legacy Browser Support: Web workers are not supported in older browsers or certain environments, so if you need to maintain compatibility with such systems, using web workers may not be feasible.

  4. Synchronous Operations: Web workers are designed for asynchronous operations, so tasks that rely heavily on synchronous operations or tight coupling with the main thread may not benefit from using web workers.

  5. Cross-Origin Limitations: Web workers have limitations when it comes to accessing resources from different origins due to browser security restrictions. If your application heavily relies on cross-origin data access, using web workers might be challenging.

  6. Complex Communication: While web workers enable communication with the main thread via message passing, managing complex communication patterns between multiple workers or between workers and the main thread can introduce overhead and potential synchronization issues.

Summary

Web workers are great for heavy tasks like number crunching or data processing without slowing down your webpage. Use them to keep your webpage responsive. But for simpler tasks or smaller web apps, they might be overkill. Also, if you need to support older browsers or rely on synchronous operations, consider alternatives.