Web Workers, for a responsive JavaScript application
Join the DZone community and get the full member experience.
Join For FreeThere is a big problem with JavaScript browser interpreters: while Ajax is by nature an asynchronous technology, all the other computations performed in JavaScript are not.
This is not necessarily an issue: after all, imperative languages like Java and PHP work like this; when you call a function the next line will be executed only after that function has returned. When you perform an XMLHttpRequest instead, you specify a callback and the moment the request starts XMLHttpRequest returns. In this scenarios, you specify a callback function which will be called after the server has responded.
Thus all JavaScript method calls, apart from Ajax-related ones, are by default synchronous. But when the browser is busy executing JavaScript, not only the subsequent lines of code are blocked: the user interface also freezes. The browser tab is blocked to avoid concurrency problems, and the user can't click nor scroll nor do anything else. If the blocks lasts for more than a few seconds, usually browsers assume JavaScript code has entered an infinite loop, and present the user with a choice:

This is an usability nightmare. We use JavaScript to avoid the latency of contacting the server for executing some logic: but at the same time we don't want to block the browser and the user experience.
An alert() is a typical example of synchronous execution, which blocks the underlying application from further computation until the user clicks Ok. You know how much alert() are annoying.
Web Workers to the rescue
Fortunately, the HTML 5 umbrella of technologies bring us Web Workers. Web Workers are lightweight, in-browser threads that we can use to execute JavaScript code without blocking the main browser process. As you probably know, multithreading can be dangerous, and in fact Web Workers are severly limited in what data they can access.
Web Workers are implemented as .js files, which are included via asynchronous HTTP requests (which are hidden from you by the Web Workers Api). When you start a Web Worker with a message, you get a separate thread of execution. I'm not aware of the various browsers implementation and if they use actually different processes, but it does not even matter here; the effect is that you are presented with multiple JavaScript threads.
Web Workers cannot manipulate the DOM nor the window or document objects; everything they need is passed to them as a scalar; this simplifies the browser's implementation and ensure a rapid adoption of the standard.
Message passing is the mean of communication between the main thread and the workers. Inside a Worker, you can perform Ajax requests with the XMLHttpRequest class, or even spawn other workers.
Example
Enough talking today. Now I'll show you some code.
This is a demonstration of a simple numerical computation: calculating if a number is prime. First, it is performed asynchronously; then a second time in the browser's main thread.
I have included a text box in which you can scroll to show how the user interface freezes. While the Web Worker is running, you're free to scroll and read the content of the box; while the browser thread is busy instead, the scrolling is blocked as well as any other action on the page. You can see this is exactly the same effect as of the alert() calls.
This code is tested in Chromium and Firefox 4. The latter will tell you that the script has become unresponsive in the scenario when you're not using a Web Worker.
Note that to instance a Web Worker, the file must be retrieved by the browser from an HTTP server. If you are under a Unix-like machine, to quickly setup a small HTTP server whose root is the current folder, enter:
python -m SimpleHTTPServer
This is the main Html page:
<script type="text/javascript"> // we will use this function in-line in this page function isPrime(number) { if (number === 0 || number === 1) { return true; } var i; for (i = 2; i <= Math.sqrt(number); i++) { if (number % i === 0) { return false; } } return true; } // a large number, so that the computation time is sensible var number = "1000001111111111"; // including the worker's code var w = new Worker('webworkers.js'); // the callback for the worker to call w.onmessage = function(e) { if (e.data) { alert(number + ' is prime. Now I\'ll try calculating without a web worker.'); var result = isPrime(number); if (result) { alert('I am sure, it is prime. '); } } else { alert(number + ' is not prime.'); } }; // sending a message to the worker in order to start it w.postMessage(number); </script> <p style="height: 200px; width: 400px; overflow: scroll;"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce blandit tristique risus, a rhoncus nisl posuere sed. Praesent vel risus turpis, et fermentum lectus. Ut lacinia nunc dui. Sed a velit orci. Maecenas quis diam neque. Vestibulum id arcu purus, quis cursus arcu. Etiam luctus, risus eu scelerisque scelerisque, sapien felis tincidunt ante, vel pellentesque eros nunc at magna. Nam tincidunt mattis velit ut condimentum. Vivamus ipsum ipsum, venenatis vitae placerat eu, convallis quis metus. Quisque tortor sapien, dapibus non vehicula quis, dapibus at purus. Nunc posuere, ligula sed facilisis sagittis, justo massa placerat nulla, nec pellentesque libero erat ut ligula. Aenean molestie, urna quis molestie auctor, lorem purus hendrerit nisi, vitae tincidunt metus massa et dolor. Sed leo velit, iaculis tristique elementum tincidunt, ornare et tellus. Quisque lacinia felis at est faucibus in facilisis dui consectetur. Phasellus sed ante id tortor pretium ornare. Aliquam ante justo, aliquam ut mollis semper, mattis sit amet urna. Pellentesque placerat, diam nec consectetur blandit, libero metus placerat massa, quis mattis metus metus nec lorem. </p>
And this is the Web Worker implementation, webworkers.js:
function isPrime(number) { if (number === 0 || number === 1) { return true; } var i; for (i = 2; i <= Math.sqrt(number); i++) { if (number % i === 0) { return false; } } return true; } // this is the point of entry for the workers onmessage = function(e) { // you can support different messages by checking the e.data value number = e.data; result = isPrime(number); // calling back the main thread postMessage(result); };
Opinions expressed by DZone contributors are their own.
Comments