Creating and working with workers

To run a complex, long-running JavaScript task without locking up the UI in the browser create a new worker.

var worker = new Worker('sample_worker.js');
A new worker object is fired up, reads in the sample_worker.js

Unlike normal javascript you cannot call methods inside the worker from your document and data cannot be returned from the worker to your document. To work with a worker, everything must be communicated through posting messages between the worker and your document. The only way to send a information to the worker is using postMessage inside a worker.

worker.postMessage('hello worker!');
The only way to receive information from the worker is using the onmessage event handler.
worker.onmessage = function (event) {
alert('The worker just sent me this: ' + event.data);
}

The code inside the worker must also communicate using the postMessage/onmessage combo. The only other method available to you via the worker object is terminate method.

inside a worker
Within a Web Worker you don’t have access to such pleasures as the DOM. In fact, if you need to do anything with the DOM, you’re going to have to prepare the work in the worker, then pass it to the parent document to do the actual DOM manipulation.

However there are a number of things you can do in a worker (according to the specifi cation):
postMessage and listen for inbound messages via onmessage
close, to end the current worker
• Set event listeners
XMLHttpRequest, for Ajax requests
• Timers, such as setTimeout, setInterval, and their clearing counterparts
• All the core JavaScript functions: eval, isNaN, escape, etc.
• Location object, the href of the worker script
• Web Sockets (which we’ll discuss in the final section of this chapter)
• Web SQL Databases
• Web Workers
• importScripts

sample_worker.js
snippet
onmessage = function(event) {
if (event.data == "hello worker!") {
postMessage("hello there, right back at you");
} else {
postMessage("Can’t you see I’m busy, leave me alone");
}
};

The this keyword would refer to the global scope in the normal , the window object where as in the worker, the global scope is the worker instance. It also means that the this keyword inside of setTimeout and setInterval.

Workers may use timeouts and intervals, including setTimeout(...), clearTimeout(...), setInterval(...), and clearInterval(...). This would be useful if, for instance, you wanted to have a worker running in the background every so often, notifying the page each time it runs.
snippet
self.onmessage = function(evt) {
setInterval(function() {
self.postMessage(Math.random()); // send a random number back
}, 60 * 60 * 1000); // execute once per hour
}
Related Tutorial