Hey Folks,
When I started discussing web workers at SparkIT – 2010, I asked about it from the listeners. They came up with funny answers and out of which one was “Web Workers are people, who develop WEB for us”. It might sound funny but Web Workers are really here to change the way we look at JavaScript programming.
As if now, JavaScript is looked upon as a language with lesser flexibility. But lot many associations are trying build JavaScript a better language. One of the major change which will change the way we used JavaScript is Web Workers.
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> <head> <title>Digimantra - Worker example </title> </head> <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.
<script> 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); } </script> |
Hope you liked the concept of Workers and you can try implementing this in Firefox for now. This definitely added one more feather in JavaScript’s cap.
Stay Digified !!
Sachin Khosla