webworker2: improved JavaScript Worker object

This is a simple library that improves the JavaScript Worker object, for creating web workers (basically allowing code to execute without blocking). It defines two new objects: Worker2 and WorkerFunction.

About

The first, Worker2, is a slight simplification of the built-in Worker object. The constructor takes three parameters: the name of the script to execute, an optional callback function for when the worker uses postMessage(), and an optional callback function for when an error occurs in the worker. The onmessage callback will be passed two parameters: the data sent and the event object. The onerror callback will be passed just the event object.

Example:

worker = new Worker2("myscript.js", function(data, e) { alert(data; });

Worker2 has four methods. The first two are postMessage() and the alias post(). These accept one parameter: the data to be sent. The other two methods are terminate() and stop(), both of which end the worker.

The other object, WorkerFunction, is more complex. It also takes three parameters, but the first is a function instead of a string. This function is used as the worker, so another file isn’t required. The two callbacks are used exactly the same way.

Example:

var myFunction = function(a, b, c) {
    return a + b + c;
};
var myCallback = function(data, e) {
    document.body.innerHTML = "<strong>" + data + "</strong>"
};
var worker = new WorkerFunction(myFunction, myCallback, function(e) { alert("Error: " + e.data); });
worker.post([1,2,3])

WorkerFunction has the same four methods as Worker2. postMessage() and post() work differently, however: they are used to pass parameters to the function if needed. They must only be passed one argument, an array of the parameters. Alternatively, they can be passed nothing if no parameters are needed.

Download

You can download webworker2 here.

Advertisements