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 thebgButton
, the background change triggered by thebgButton
could be delayed or impeded until thesumButton
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 aworker.js
file, set theonmessage
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 processingSend the result back once processed:
Inside theonmessage
event handler inworker.js
, thepostMessage
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 ?
Line 1: Create a worker
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:
Script File (main.js):
Sends a message using
postMessage
.Waits for a response from the worker using an event listener (
onmessage
).
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
.
Script File (main.js):
- Receives the processed message from the worker using
onmessage
.
- Receives the processed message from the worker using
Use cases
Parallel Processing: Web workers enable parallel processing of tasks such as data parsing, image processing, or mathematical calculations, improving overall performance and responsiveness.
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.
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
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.
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.
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.
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.
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.
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.
Subscribe to my newsletter
Read articles from Ankita Sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Ankita Sharma
Ankita Sharma
Unlocking the world of coding, one line at a time.