Home arrow JavaScript arrow Javascript and HTML5: Closing Multiple Web Workes
JAVASCRIPT

Javascript and HTML5: Closing Multiple Web Workes


Web workers are powerful JavaScript objects included with HTML5, which can be used for running multiple processes in parallel, entirely separate from the browser UI thread. In turn, you can make any number of web workers interact with a main web page through a simple and intuitive messaging API. In this article, we will take a closer look at the "close" method, which we will use to interact with not one, but multiple workers.

Author Info:
By: Alejandro Gervasio
Rating: 5 stars5 stars5 stars5 stars5 stars / 3
July 18, 2011

print this article
SEARCH DEVARTICLES

Web workers are powerful JavaScript objects included with HTML5, which can be used for running multiple processes in parallel, entirely separate from the browser UI thread. In turn, you can make any number of web workers interact with a main web page through a simple and intuitive messaging API. In this article, we will take a closer look at the "close" method, which we will use to interact with not one, but multiple workers.


If you had the opportunity to read some of the previous installments of this series, at this point you have a thorough background on using web workers, since in the mentioned tutorials I developed some approachable examples, which not only demonstrated how to interact with multiple workers from a main web page, but how to close their associated threads via the “close()” method. If you missed those articles, you can view them here: 

In those tutorials, I illustrated how to use the mentioned method for stopping a single web worker, which is all well and fine. It’s feasible, however, to set up a script that has the capability for stopping multiple workers with the same ease. Therefore, in the course of this penultimate episode of the series, I’m going to develop another basic example, which will show you how to close the threads tied up to three different workers, so that you can see how simple it is to accomplish this task.

Working with the “close()” Method: Stopping a Single Web Worker

Prior to demonstrating how to close the threads associated to multiple web workers, first I’d like to spend a few moments recalling the example created in the preceding tutorial, which showed how to perform the same task, but using only a single worker.

The driving logic of this example was built around passing a string command from a main script, which could be interpreted by the worker as an order to shut down its pertaining thread. The following web page implements this “commander” script. Check it out:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Example stopping 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.');

// stop the worker
worker.postMessage('QUIT'); 
</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>

Once the corresponding worker has been instantiated, it receives three messages from the web page. The first two are quite trivial, thus they don’t deserve any further explanation. The third message, however, is a bit more relevant, as it’s an arbitrary command that instructs the worker to close its associated thread.

If at this point, you’re wondering how this command is interpreted and processed on the worker’s side, pay attention to the object’s file. Here it is:

(worker1.js)

// get messages from the main script
self.onmessage = function(e) {
    if (e.data == 'QUIT') {
       self.postMessage('Web worker 1 says: stopping work right now...');
       self.close();
    }
}

// do some other stuff here

Whenever the worker gets a “QUIT” message from the main script, it proceeds to stop its associated thread via the aforementioned “close()” method. Below there’s an image that will help you understand how the prior example does its thing. Take a peek: 



Now that you know how to stop a single worker, it’s time to create another example capable of doing the same thing, but with multiple ones.

Taking the “close()” Method to the Next Level: Stopping Multiple Web Workers

Closing multiple workers from a main script is a process that doesn’t differ too much from performing the same task with a single object. The best manner to understand the details of this process is by example, so below I wrote one, which uses the already familiar “QUIT” string to close the threads of three different workers. Here’s the web page containing the main script: 

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Example stopping multiple Web Workers</title>
<script>
// display messages from the workers
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 workers
var worker1 = new Worker('worker1.js');
var worker2 = new Worker('worker2.js');
var worker3 = new Worker('worker3.js');

// get messages from the web workers
worker1.onmessage = function(e) {
    displayMessage(e.data);
}
worker2.onmessage = function(e) {
    displayMessage(e.data);
}
worker3.onmessage = function(e) {
    displayMessage(e.data);
}

// send some messages to the web workers
worker1.postMessage('Hello worker 1, how are you doing?');
worker2.postMessage('Hi worker 2, is everything fine over there?');
worker3.postMessage('Hey worker 3, keep doing what you are doing.');

// stop the workers
worker1.postMessage('QUIT');
worker2.postMessage('QUIT');
worker3.postMessage('QUIT');
</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>

In the above example, the script simply dispatches a “QUIT” order to the corresponding workers, after sending them a few simple (and rather robotic) messages.

Of course, the missing elements of this example are the files used by the workers. Again, don’t feel concerned about this issue, since the definitions of the files in question will be shown in the next section.

Adding the Missing Pieces to the Earlier Example: Showing the Workers’ Associated Files

Here are the definitions of the files corresponding to the previously created workers. Not surprisingly, they respond identically to the “QUIT” command piped out by the main script:

(worker1.js)

// get messages from the main script
self.onmessage = function(e) {
    if (e.data == 'QUIT') {
       self.postMessage('Web worker 1 says: stopping work right now...');
       self.close();
    }
}

// do some other stuff here



(worker2.js)

// get messages from the main script
self.onmessage = function(e) {
    if (e.data == 'QUIT') {
       self.postMessage('Web worker 2 says: stopping work right now...');
       self.close();
    }
}

// do some other stuff here



(worker3.js)

// get messages from the main script
self.onmessage = function(e) {
    if (e.data == 'QUIT') {
       self.postMessage('Web worker 3 says: stopping work right now...');
       self.close();
    }
}

// do some other stuff here

Mission accomplished. In a few easy steps, I managed to build a simple JavaScript program, which has the ability to close the threads corresponding to some basic web workers. But wait a minute! Before I forget, take a look at the following screen capture, which shows how each worker reacts to the “QUIT” command:



That’s pretty self explanatory, right? Even when the earlier example is really simplistic, it comes in handy for demonstrating how to use the “close()” method with multiple web workers. At this point, and armed with this material, you might want to create more complex workers that respond to a set of predefined commands, instead of only one.

Final Thoughts

In this penultimate chapter of the series, I went through the development of another basic example, which demonstrated how to stop (from a main web page) three different workers by using the “close()” method. As you jut saw, the whole process was reduced to dispatching a specific command to the objects via the bi-directional messaging API and nothing else.

It’s fair to denote that all the examples developed so far didn’t implement workers capable of doing more complex things in parallel. To fix this issue and make things a bit more realistic, in the final chapter of this series I’m going to show you how to take advantage of the functionality of a few workers to calculate the factorial of different numbers at the same time.

Want to see how this will be done? Then don’t miss the last tutorial! 
 


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

All JavaScript Tutorials
More By Alejandro Gervasio


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