HTML5 LogoBy instantiating the Worker() constructor twice, we can see how more than one number-crunching task can be passed off to separate threads, once again leaving the browser responsive and completely available to the user.

In Part II of this article, we discovered the liberating effect of implementing a single Web Worker. We were able to pass our number crunching work off to the Worker, which ran in a separate thread. As a result, the browser remained responsive (e.g. we were able to resize the box while the numbers were being crunched). In this third and final part of the article, we will take things one step further by spawning two number-crunching threads, all the while continuing to keep the browser completely responsive.

Part III: Multiple Web Workers

Example # 1

In Example # 1, we have for the most part, replicated the approach taken in Part II of this article. The only difference here is that we have created two instances of the Worker() constructor (myWorkerOne and myWorkerTwo). We are using the same physical worker file (i.e. worker.js), so the argument passed to the Worker() constructor is the same in both cases. From there the steps are the same. We create our event listeners, and from each “Crunch some numbers” button, a message is sent to the appropriate Worker instance.

Click here to see the full working demo for Part III of this article: http://examples.kevinchisholm.com/javascript/web-workers/basic/example-3.php

When you clicked both of the “Crunch some numbers” buttons, a separate number-crunching task was passed off to a Worker in a new thread. You can see that the Ajax loader gif spins with no problem, and you are able to resize the boxes as much as you wish.

Click here to compare the examples from all three of the parts of this article: http://examples.kevinchisholm.com/javascript/web-workers/basic/example-1.php?menu

Summary

In this article, we demonstrated how multiple Workers can be used simultaneously. Just as in the example from Part II of this article, we proved that while the Worker is crunching numbers, the browser is completely responsive and available to the user.

The examples in all three parts of this article were very simple and meant only to introduce the topic of Web Workers. There is a great deal more to talk about with regard to Web Workers and I do plan to do so here in this blog in the coming weeks.

More Helpful Links for Implementing HTML5 Web Workers

http://www.htmlgoodies.com/html5/tutorials/introducing-html-5-web-workers-bringing-multi-threading-to-javascript.html#fbid=CwNX9_fBBqp

http://html5demos.com/worker

http://caniuse.com/#feat=webworkers