JavaScript Web Workers: A Beginner’s Guide

JavaScript Web Workers: A Beginner’s Guide

Learn how web workers help with web app performance, and get started by building a basic JavaScript web worker.

Learn how web workers help with web app performance, and get started by building a basic JavaScript web worker.

In 2019, the web ecosystem has evolved to the point where the browser is an execution environment for applications built on JavaScript. This is reflected in the speed with which the industry comes up with new frameworks, paradigms, module loaders and bundlers, dependency managers, build tools, and package managers year after year.

When JavaScript was conceived in the early days of the internet, the direction of internet development was not clear. Due to the constant, rapid change in the industry and ecosystem, the need for the backward-compatibility of browsers and web standards, the evolution of JavaScript became a constant stream of patches, hacks and afterthoughts.

Today’s mobile devices normally come with 8+ CPU cores, or 12+ GPU cores. Desktop and server CPUs have up to 16 cores, 32 threads, or more.

In this environment, having a dominant programming or scripting environment that is single-threaded is a bottleneck.

JavaScript Is Single-threaded

This means that by design, JavaScript engines — originally browsers — have one main thread of execution, and, to put it simply, process or function B cannot be executed until process or function A is finished. A web page’s UI is unresponsive to any other JavaScript processing while it is occupied with executing something — this is known as DOM blocking.

This is terribly inefficient, especially compared to other languages.

If we go to JS Bin and run this code in the browser’s JavaScript console:

//noprotect
i = 0;
while (i < 60000) {
  console.log("The number is " + i);
  i++;
}


… the whole jsbin.com website will become unresponsive until the browser counts — and logs — to 60,000.

We won’t be able to interact with anything on the page, because the browser is busy.

Now, this is a relatively undemanding computing process, and today’s web apps often involve much more demanding tasks.

We need to be able to compute things in the background while the user seamlessly interacts with the page.

Web Workers

The W3C published a first draft of the web workers standard in 2009. The full specification can be found on the Web Hypertext Application Technology Working Group website — or WHATWG — a web standards body alternative to W3C.

Web workers is an asynchronous system, or protocol, for web pages to execute tasks in the background, independently from the main thread and website UI. It is an isolated environment that is insulated from the window object, the document object, direct internet access and is best suited for long-running or demanding computational tasks.

Apart from web workers — a system dedicated to multithreading — there are other ways to achieve asnychronous processing in JavaScript, such as asynchronous Ajax calls, and event loop.

To demonstrate this, we will go back to JS Bin and try this snippet:

console.log("A");
setTimeout(function(){console.log("B");},2000);
console.log("C");
setTimeout(function(){console.log("D");},0);
console.log("E");
setTimeout(function(){console.log("F");},1000);


When we run this, our log sequence is A, C, E, D, F, B. The browser first schedules operations without the timeout, as they come, and then it executes the setTimeout() functions in the order of their respective specified delays. However, this asynchronicity should not be automatically conflated with multithreading. Depending on the host machine, this can often be just a single-thread stack of the calls in the order we explained.

Web Workers & Multithreading

As Mozilla’s JavaScript reference website explains, web workers are a “means for web content to run scripts in background threads.”

We use them in the following way: we check for the availability of the Worker() constructor in the browser, and if it is available, we instantiate a worker object, with the script URL as the argument. This script will be executed on a separate thread.

The script must be served from the same host or domain for security reasons, and that is also the reason that web workers won’t work if we open the file locally with a file:// scheme.

if (typeof(Worker) !== "undefined") {  
    worker = new Worker("worker.js");
}            


Now we define this code in the worker.js file:

i = 0;
while (i < 200000) {
    postMessage("Web Worker Counter: " + i);
    i++;
}


The Separation of Threads

An important thing to note here is the separation of the window and document scope of execution in the main browser window thread, and the worker scope.

In order to make use of the worker thread, these two scopes need to be able to communicate. To achieve this, we use the postMessage() function within the worker.js file — to send messages to the main browser thread — and the worker.onmessage listener in the main thread to listen to worker messages.

We can also send messages from the main browser thread to the worker thread or function. The only difference is that we reverse things, and call worker.postMessage() on the main thread, and onmessage on the worker thread. To quote Mozilla’s developer reference:

Notice that onmessage and postMessage() need to be hung off the Worker object when used in the main script thread, but not when used in the worker. This is because, inside the worker, the worker is effectively the global scope.
We can use the terminate() method in the same way, to end our worker’s execution.

With all this in mind, we come to this example:

index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Web Workers Example</title>

    <style type="text/css">
    body {padding-top:28px;}
    .output-cont {margin-left:12%; margin-top:28px;}

    .output-cont h3 {width:200px; height:100%;}
    .output-cont button {padding:4px 8px; font-size:1.1rem; font-family:sans-serif;  }

    </style>
</head>

<body>

<div class="output-cont"><button onclick="testWorker()">start worker</button><h3 id="workerOutput"></h3><button onclick="terminateWorker()">terminate worker</button></div>
<br/>
<div class="output-cont"><button onclick="testMainThread()">start blocking thread</button><h3 id="mainThreadOutput"></h3></div>
<br/>
<div class="output-cont"><button onclick="alert('browser responsive!')">test browser responsiveness</button></div>

  <script>

    var worker;

    function testWorker() {
        if (typeof(Worker) !== "undefined") {
            if (typeof(worker) == "undefined") {
                worker = new Worker("worker.js");
            }
            worker.onmessage = function(event) {
                document.getElementById("workerOutput").innerHTML = event.data;
            };
        } else {
            document.getElementById("workerOutput").innerHTML = "Web Workers are not supported in your browser";
        }
    }
    function terminateWorker() { 
        worker.terminate();
        worker = undefined;
    }

    function testMainThread() {
        for (var i = 0; i < 200000; i++) { 
            document.getElementById("mainThreadOutput").innerHTML = "Main Thread Counter: " + i;

        }
    }

  </script>

</body>

</html>


and worker.js:

i = 0;
while (i < 200000) {
    postMessage("Web Worker Counter: " + i);
    i++;
}


This gives us the opportunity to test out the effects of main-thread execution on page behavior and performance versus the web worker’s effects.

In this tutorial, we used http-server to serve the files locally.

Now we can see that the worker thread does not block the interactivity of the main browser process, and looping through 200,000 numbers does not affect the main thread. The numbers in the #workerOutput element are updated on every iteration.

The blocking thread, or main thread, when engaged in a loop, blocks all interactivity (we have set the number of iterations to 200,000 here, but it will be even more obvious if we increase it to 2,000,000).

One more thing that points us to a blocked main thread is that the worker process updates the page on every iteration, and the loop in the main thread (the one defined in index.html) only updates the #mainThreadOutput element on the last iteration.

This is because the browser is too consumed with counting (for loop) to be able to redraw the DOM, so it does it only once its business with the for loop is fully done (at the end of the loop).

Conclusion

In this article, we introduced web workers, a technology that helps the web industry keep up with more and more demanding web apps. This is done by providing a way for web apps to leverage multi-processor and multi-threaded devices by bestowing some multi-threaded superpowers to JavaScript.

Web workers turn the mobile and desktop browser environments into application platforms, providing them with a strict execution environment. This strictness may force us to provide for the copying of objects between multiple threads, and to plan our applications with these constraints in mind.

Do you have any tips regarding web workers, and the web as a programming platform? Let us know in the comments!

Mobile App Development Company India | Ecommerce Web Development Company India

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company

JavaScript developers should you be using Web Workers?

JavaScript developers should you be using Web Workers?

Do you think JavaScript developers should be making more use of Web Workers to shift execution off of the main thread?

Originally published by David Gilbertson at https://medium.com

So, Web Workers. Those wonderful little critters that allow us to execute JavaScript off the main thread.

Also known as “no, you’re thinking of Service Workers”.

Photo by Caleb Jones on Unsplash

Before I get into the meat of the article, please sit for a lesson in how computers work:

Understood? Good.

For the red/green colourblind, let me explain. While a CPU is doing one thing, it can’t be doing another thing, which means you can’t sort a big array while a user scrolls the screen.

This is bad, if you have a big array and users with fingers.

Enter, Web Workers. These split open the atomic concept of a ‘CPU’ and allow us to think in terms of threads. We can use one thread to handle user-facing work like touch events and rendering the UI, and different threads to carry out all other work.

Check that out, the main thread is green the whole way through, ready to receive and respond to the gentle caress of a user.

You’re excited (I can tell), if we only have UI code on the main thread and all other code can go in a worker, things are going to be amazing (said the way Oprah would say it).

But cool your jets for just a moment, because websites are mostly about the UI — it’s why we have screens. And a lot of a user’s interactions with your site will be tapping on the screen, waiting for a response, reading, tapping, looking, reading, and so on.

So we can’t just say “here’s some JS that takes 20ms to run, chuck it on a thread”, we must think about where that execution time exists in the user’s world of tap, read, look, read, tap…

I like to boil this down to one specific question:

Is the user waiting anyway?

Imagine we have created some sort of git-repository-hosting website that shows all sorts of things about a repository. We have a cool feature called ‘issues’. A user can even click an ‘issues’ tab in our website to see a list of all issues relating to the repository. Groundbreaking!

When our users click this issues tab, the site is going to fetch the issue data, process it in some way — perhaps sort, or format dates, or work out which icon to show — then render the UI.

Inside the user’s computer, that’ll look exactly like this.

Look at that processing stage, locking up the main thread even though it has nothing to do with the UI! That’s terrible, in theory.

But think about what the human is actually doing at this point. They’re waiting for the common trio of network/process/render; just sittin’ around with less to do than the Bolivian Navy.

Because we care about our users, we show a loading indicator to let them know we’ve received their request and are working on it — putting the human in a ‘waiting’ state. Let’s add that to the diagram.

Now that we have a human in the picture, we can mix in a Web Worker and think about the impact it will have on their life:

Hmmm.

First thing to note is that we’re not doing anything in parallel. We need the data from the network before we process it, and we need to process the data before we can render the UI. The elapsed time doesn’t change.

(BTW, the time involved in moving data to a Web Worker and back is negligible: 1ms per 100 KB is a decent rule of thumb.)

So we can move work off the main thread and have a page that is responsive during that time, but to what end? If our user is sitting there looking at a spinner for 600ms, have we enriched their experience by having a responsive screen for the middle third?

No.

I’ve fudged these diagrams a little bit to make them the gorgeous specimens of graphic design that they are, but they’re not really to scale.

When responding to a user request, you’ll find that the network and DOM-manipulating part of any given task take much, much longer than the pure-JS data processing part.

I saw an article recently making the case that updating a Redux store was a good candidate for Web Workers because it’s not UI work (and non-UI work doesn’t belong on the main thread).

Chucking the data processing over to a worker thread sounds sensible, but the idea struck me as a little, umm, academic.

First, let’s split instances of ‘updating a store’ into two categories:

  1. Updating a store in response to a user interaction, then updating the UI in response to the data change
  2. Not that first one

If the first scenario, a user taps a button on the screen — perhaps to change the sort order of a list. The store updates, and this results in a re-rendering of the DOM (since that’s the point of a store).

Let me just delete one thing from the previous diagram:

In my experience, it is rare that the store-updating step goes beyond a few dozen milliseconds, and is generally followed by ten times that in DOM updating, layout, and paint. If I’ve got a site that’s taking longer than this, I’d be asking questions about why I have so much data in the browser and so much DOM, rather than on which thread I should do my processing.

So the question we’re faced with is the same one from above: the user tapped something on the screen, we’re going to work on that request for hopefully less than a second, why would we want to make the screen responsive during that time?

OK what about the second scenario, where a store update isn’t in response to a user interaction? Performing an auto-save, for example — there’s nothing more annoying than an app becoming unresponsive doing something you didn’t ask it to do.

Actually there’s heaps of things more annoying than that. Teens, for example.

Anyhoo, if you’re doing an auto-save and taking 100ms to process data client-side before sending it off to a server, then you should absolutely use a Web Worker.

In fact, any ‘background’ task that the user hasn’t asked for, or isn’t waiting for, is a good candidate for moving to a Web Worker.

The matter of value

Complexity is expensive, and implementing Web Workers ain’t cheap.

If you’re using a bundler — and you are — you’ll have a lot of reading to do, and probably npm packages to install. If you’ve got a create-react-app app, prepare to eject (and put aside two days twice a year to update 30 different packages when the next version of Babel/Redux/React/ESLint comes out).

Also, if you want to share anything fancier than plain data between a worker and the main thread you’ve got some more reading to do (comlink is your friend).

What I’m getting at is this: if the benefit is real, but minimal, then you’ve gotta ask if there’s something else you could spend a day or two on with a greater benefit to your users.

This thinking is true of everything, of course, but I’ve found that Web Workers have a particularly poor benefit-to-effort ratio.

Hey David, why you hate Web Workers so bad?

Good question.

This is a doweling jig:

I own a doweling jig. I love my doweling jig. If I need to drill a hole into the end of a piece of wood and ensure that it’s perfectly perpendicular to the surface, I use my doweling jig.

But I don’t use it to eat breakfast. For that I use a spoon.

Four years ago I was working on some fancy animations. They looked slick on a fast device, but janky on a slow one. So I wrote fireball-js, which executes a rudimentary performance benchmark on the user’s device and returns a score, allowing me to run my animations only on devices that would render them smoothly.

Where’s the best spot to run some CPU intensive code that the user didn’t request? On a different thread, of course. A Web Worker was the correct tool for the job.

Fast forward to 2019 and you’ll find me writing a routing algorithm for a mapping application. This requires parsing a big fat GeoJSON map into a collection of nodes and edges, to be used when a user asks for directions. The processing isn’t in response to a user request and the user isn’t waiting on it. And so, a Web Worker is the correct tool for the job.

It was only when doing this that it dawned on me: in the intervening quartet of years, I have seen exactly zero other instances where Web Workers would have improved the user experience.

Contrast this with a recent resurgence in Web Worker wonderment, and combine that contrast with the fact that I couldn’t think of anything else to write about, then concatenate that combined contrast with my contrarian character and you’ve got yourself a blog post telling you that maybe Web Workers are a teeny-tiny bit overhyped.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

An Introduction to Web Workers

JavaScript Web Workers: A Beginner’s Guide

Using Web Workers to Real-time Processing

How to use Web Workers in Angular app

Using Web Workers with Angular CLI