JavaScript’s Secret Weapon: Supercharge Your Web Apps with Web Workers

During an interview, I was asked how we could make JavaScript multi-threaded. I was stumped, and admitted I didn’t know… JavaScript is a single-threaded language. Indeed, JavaScript is a single-threaded language, it can only execute a single task at a time. However, multi-threaded behavior can be achieved with the use of something called Web Workers.

Web Workers are a JavaScript feature that enable concurrent execution of scripts in web applications (wait, it’s not really a secret, is it? 😅). They allow us to run scripts in the background separate from the main execution thread of the web page, thereby preventing blocking of the user interface (UI) and improving responsiveness.

Whoah, that’s extremely interesting, right?! If you were like me, this is new knowledge to you, and for sure a moment of revelation.

Let’s take a look at an example, and afterwards explore the usefulness of Web Workers.

A Look At Web Workers: An Example

If you’re going to want to try out the code below, please note you’ll need to run a server, else the code won’t execute. The simplest way to do this is to globally install the http-server package via npm. You can do that by running the following command (assuming you have Node.js installed):

npm i -g http-server

Of course, feel free to spin up a Node.js server and configure the code, but for this article, we’ll use the http-server package.

Let’s start by creating a folder called web-worker (or whatever you prefer). In this folder, we’re going to create two files, index.html, and evenOddWorker.js

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Web Worker</title>
  </head>
  <body>
    <h1>Even/Odd Checker</h1>
    <label for="numberInput">Enter a number:</label>
    <input type="number" id="numberInput" />
    <button id="checkButton">Check</button>

    <p id="result"></p>
  </body>
</html>

Above is nothing too complicated, it’s just some basic markup. Although it doesn’t hurt to explain what is going on with it. Basically, we have a single <input> element which is where a user is going to enter a number. Next, we have a button, which of course will execute some JavaScript code when it is clicked. Finally, we have an empty paragraph, which, as you can guess, is where the message will appear if a number is even or odd.

The code which defines most of this is going to be inserted within the HTML code above, right above the closing body tag (i.e. </body>).

<!-- Previous code -->

<script>
  document.getElementById("checkButton").addEventListener("click", function () {
    const number = parseInt(document.getElementById("numberInput").value);
    if (!isNaN(number)) {
      const worker = new Worker("evenOddWorker.js");
      worker.postMessage(number);
      
      worker.onmessage = function (event) {
        const result = event.data ? "even" : "odd";
        document.getElementById(
          "result"
        ).textContent = `The number is ${result}.`;
      };
    } 
    
    else {
      alert("Please enter a valid number.");
    }
  });
</script>
<!-- Closing body and html tags here -->

This script sets up an event listener on the button. When the button is clicked, the code retrieves the value entered in an input field. It then checks if the value is a valid number using the parseInt() function. If the value is indeed a number, it creates a new web worker using the script we’ll create shortly.

The web worker will work in the background, handling the computation of whether the number is even or odd.

The code then sends the number entered by the user to the web worker using worker.postMessage(number). After that, it sets up an event handler using worker.onmessage to receive the result computed by the web worker.

When the web worker finishes its computation and sends a message back, the event handler executes. It retrieves the result from the message data and updates the content of the empty paragraph to display whether the number is even or odd.

If the entered value is not a valid number, the code displays an alert asking the user to enter a valid number.

Now, we’ve created most of the logic for this small web application. The only thing we’re missing is the code which is going to go within evenOddWorker.js, so let’s go ahead and add the following code into the file:

// evenOddWorker.js
onmessage = function(event) {
    const number = event.data;
    const isEven = number % 2 === 0;
    postMessage(isEven);
};

That’s it – a very short file indeed, but we wanted to keep this example short and to the point. Nevertheless, we should explain what’s happening.

Within evenOddWorker.js, there’s an event listener assigned to the onmessage event. This event is triggered whenever the main thread sends a message to the worker, which happens in the main script when the user clicks the “check” button.

When the worker receives a message, it extracts the data from the event using event.data. This data is assumed to be a number, as per the usage in the main script, and finally, the rest of the code executes to check whether if the number entered is even or odd.

Web Worker Example

There we have it, a functioning site which makes use of a Web Worker in JavaScript.

Why Are Web Workers Useful?

Think about it like having a team of assistants working behind the scenes.

Imagine you’re building a web application that needs to process large amounts of data or perform complex calculations.

These tasks can be quite resource-intensive and may cause the user interface to become unresponsive, leading to a frustrating experience for your users. This is why web workers are so handy. They allow you to run JavaScript code concurrently in the background, separate from the main browser thread. This means that while your main thread is busy handling user interactions and rendering the interface, web workers can take care of heavy lifting tasks without causing any delays or freezes.

Think about it like having a team of assistants working behind the scenes.

Web workers also enable you to harness the full potential of multi-core processors. While traditional JavaScript execution is single-threaded, web workers allow you to leverage the power of multiple CPU cores by running tasks in parallel. This not only improves performance but also enhances scalability, as you can easily distribute computational load across multiple threads.

Web Worker Example

In practical terms, web workers find numerous applications across various domains. From real-time data analysis in financial applications to image processing in photo-sharing platforms, web workers offer a solution for improving the performance and responsiveness of web applications.

Conclusion

Web workers are like your silent partners, working tirelessly in the background to ensure that your web application delivers a seamless and engaging experience for users. In this article, we took a look at Web Workers, something which will enhance your skills and value as a web developer.

Have you ever worked with web workers? Let us know in the comments below!

comments powered by Disqus

Related Posts

Creating a Real Time Chat Application with React, Node, and TailwindCSS

In this tutorial, we will show you how to build a real-time chat application using React and Vite,as well as a simple Node backend.

Read more

The Importance of Staying Active as a Software Developer

In today’s fast-paced digital world, developers often find themselves glued to their screens for extended periods. While this dedication is commendable, it comes with its own set of challenges.

Read more

JavaScript DOM Mastery: Top Interview Questions Explained

Mastering the Document Object Model (DOM) is crucial for any JavaScript developer. While many developers rely heavily on front-end frameworks, the underlying DOM concepts are still important.

Read more