Introduction to Web Workers in JavaScript

The term ‘Web Workers’ is new to most of the web developers as well as web clients. Even I could not interpret it correctly when I heard of it the first time. I was searching for something on the web when I found an interesting tutorial about web workers on Digimantra.com by Sachin Khosla. I thought it would be interesting to share the concept of web workers with my readers.

Web Workers allow programmers to build more responsive and efficient web applications. Workers allow this by adding the power of threading in native JavaScript code such that a script is run in the background process. This is similar to running different threads of a process. Web Workers got introduced in FireFox 3.5 ‘s JavaScript engine.
Workers can perform the following task:
1. Perform any JavaScript tasks without interrupting user interface.
2. Perform I/O using XMLHttpRequest (however, the responseXML and channel attributes are always null).
3. Can create sub-workers as long as those workers are hosted within the same origin as the parent page (sub-workers URIs are relative to the parent worker location).
4. Can use timeouts and intervals.
However there are some limitations to this and that is Workers cannot manipulate DOM elements directly. It can only process and return the output.

Web Worker event and methods
Events
a) onmessage: this event will be raised when a message is posted from or to the worker.
b) onerror: this event will be raised when an error occurred in the worker.

Methods
a) postMessage: this method is used to send a message from or to the worker.
b) terminate: kills the worker immediately without waiting it to finish its task.
c) close: similar to terminate method but is used from within the worker itself.

Ok, we have enough of theory now let’s see how it works. We need :
* Worker File (which contains the process intense script)
* A HTML file (workers.html), having JavaScript function explaining how to make Workers up & running.
* A HTML file (no_workers.html), which shows what happens if the same script runs without Workers.(NOTE: opening/running this file, might end up making your browser unresponsive.)
In Worker file we have is a script to find prime numbers. This JavaScript function keeps on finding prime numbers and post it to back (using postMessage) to the main function (which spawned the Worker).

var n = 1;
search: while (true)
{
n += 1;
for (var i = 2; i <= Math.sqrt(n); i += 1)
if (n % i == 0)
continue search;
// found a prime!
postMessage(n);

}

The HTML file as shown below, Spawns the Worker by specifying the Worker’s filename. Be sure to pass the filename with correct path, otherwise it will give an error message.

<!DOCTYPE HTML>
<html>
<body>
<p>The highest prime number discovered so far is: <output id="result"></output></p>
<script>
var worker = new Worker('workers.js');
worker.onmessage = function (event) {
document.getElementById('result').textContent = event.data;
};
function term()
{
worker.terminate();
}
</script>
<p><input type="button" onclick="term();" value="Terminate" /></p>
</body>
</html>

Now let’s paste the content of the worker file into a simple HTML file using the script tag. You will see that the browser will become unresponsive since the script runs infinitely. However it is possible to terminate your worker anytime, just hit the terminate button and the worker will exit there only.

var n = 1;
search: while (true)
{
n += 1;
for (var i = 2; i <= Math.sqrt(n); i += 1)
if (n % i == 0)
continue search;
// found a prime!
//postMessage(n);
document.write(n);
}

Written by Arvind Bhardwaj

Arvind is a certified Magento 2 expert with more than 10 years of industry-wide experience.

Website: http://www.webspeaks.in/

One thought on “Introduction to Web Workers in JavaScript

Comments are closed.