Home arrow JavaScript arrow JavaScript Multithreading with HTML5 Web Workers
JAVASCRIPT

JavaScript Multithreading with HTML5 Web Workers


HTML5 is known for its great set of new semantic elements. What you may not be aware of, however, is its new type of JavaScript objects known as web workers. In this tutorial, you will learn how to use these new objects to multithread in JavaScript.

Author Info:
By: Alejandro Gervasio
Rating: 5 stars5 stars5 stars5 stars5 stars / 5
March 08, 2011
TABLE OF CONTENTS:
  1. · JavaScript Multithreading with HTML5 Web Workers
  2. · Interacting with Multiple HTML5 Web Workers
  3. · Creating the Web Workers with HTML5 and JavaScript

print this article
SEARCH DEVARTICLES

JavaScript Multithreading with HTML5 Web Workers
(Page 1 of 3 )

If you already had the chance to look at the introductory part of this series (HTML5 and JavaScript Web Workers), you should be familiar with the basics of using web workers, since in the course of that tutorial I set up a simple example, showing you how to create a single worker and interact with it from a main web page via the aforementioned API.

As you’ll probably recall, transferring different messages between the worker and the main script was reduced to using the API’s “onmessage” event handler and calling the “postMessage()” method at the appropriate places. That was pretty simple to grab, wasn’t it?

Of course, this basic demonstration of JavaScript multithreading can be taken one step further with minor effort. The question that probably keeps your mind spinning around is how, right? Well, as with many other JavaScript objects, it’s possible to spawn multiple workers (which naturally may also execute scripts in isolation) and talk to them from the main web page.

Considering that the best way to recreate the previous scenario is by example, in the next few lines I’ll be developing an approachable one, which will show you how to interact with three web workers at the same time from a main script.

Basic Parallelism in JavaScript: Interacting with a Single HTML5 Web Worker   

As I explained in the introduction, “speaking” to a web worker from the main web page is an easy-to-achieve process that can be mastered in a snap. But, if for some reason, you missed the first part of this series, where I created an example that showed how to accomplish this in a friendly fashion, I will recap it in the section below.

With that being said, first off here’s the web page responsible for interacting with the worker. Take a look:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Example using a single Web Worker</title>
<script>
// display messages from the worker
function displayMessage(msg) {
    var section = document.getElementsByTagName('section')[0];
    if (section === null){return};
    var par = document.createElement('p');
    par.setAttribute('class', 'worker_message');
    par.appendChild(document.createTextNode(msg));
    section.appendChild(par);
}

// create the web worker
var worker = new Worker('worker1.js');

// get messages from the web worker
worker.onmessage = function(e) {
    displayMessage(e.data);
}

// send a couple of messages to the web worker
worker.postMessage('Hello worker 1, how are you doing?');
worker.postMessage('Things are pretty busy over here.');  
</script>
<style>
body {
    padding: 0;
    margin: 0;
    background: #0c1e74;
    font: 0.8em Arial, Helvetica, sans-serif;
    color: #000;
}
h1 {
    font-weight: normal;
    font-size: 2.1em;
    color: #0c1e74;
}
h2 {
   font-weight: normal;
   font-size: 1.8em;
   color: #0c1e74;
}
p {
    margin: 0 0 15px 0;
}
#wrapper {
    width: 920px;
    margin: 0 auto;
    background: #fff;
}
header, section, footer {
    display: block;
    padding: 15px;
}
.worker_message {
    color: #00f;
}
</style>
</head>
<body>
<div id="wrapper">
    <header>
        <h1>Using JavaScript Web Workers</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
    </header>
    <section>
        <h2>Worker message section</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
    </section>
    <footer>
        <h2>Footer section</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p> 
    </footer>
</div>
</body>
</html>

As you can see above, the main script embedded in the earlier HTML5 document starts by creating a simple web worker, and then sends out a couple of messages to it via the JavaScript “postMessage()” method. On its side, the worker appropriately catches those messages and replies back to the script, via the “onmessage” handler.

If, at this point, you’re wondering what the definition of the file associated to the sample worker is, don’t worry - I outline it below:

(worker1.js)

// get messages from the main script
self.onmessage = function(e) {
    self.postMessage('Web worker 1 says... message received from main script is: ' + e.data);
}

// do some other stuff here

Here, it’s clear to see that the worker is capable of talking to the main script, while at the same time it might be performing any other task, (a simple loop, a complex mathematical calculation, and so forth). Of course, this example would look rather unfinished if I did not show you the output that it produces when tested on a web-worker compatible browser (remember that currently Internet Explorer doesn’t support workers, but version 9 will):  

Although somewhat basic, the earlier code snippets show - in a nutshell - how to execute a process independently from the browser UI’s thread using a single Javascript worker. As it was stated at the beginning of this article, however, it’s possible to create a main script that interacts simultaneously with multiple workers, instead of dealing with just one.

Since this scenario is fairly easy to recreate, in the following segment I’m going to build a brand new example where the main web page will send out and receive messages from three different workers.

To learn the finer details of this process, let's move on to our next section.


blog comments powered by Disqus
JAVASCRIPT ARTICLES

- Project Nashorn to Make Java, JavaScript Wor...
- JavaScript Virus Attacks Tumblr Blogs
- Google Releases Stable Dart Version, JavaScr...
- Khan Academy Unveils New JavaScript Learning...
- Accessing Nitro? There`s an App for That
- JQuery 2.0 Leaving Older IE Versions Behind
- Fastest JavaScript Engine Might Surprise You
- Microsoft Adjusting Chakra for IE 10
- Brendan Eich: We Don`t Need Google Native Cl...
- An Overview of JavaScript Statements
- An Overview of JavaScript Operators
- Overview of JavaScript Variables
- More of the Top jQuery Social Plugins
- The Top jQuery Social Plugins
- More of the Top jQuery Slider Plugins

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials