My favorites | Sign in
Project Logo
                
Show all Featured wiki pages:
APIDoc Samples
People details
Project owners:
  AlexCheng1982

JsWorker is a small JavaScript library that wraps current implementations of worker thread in browsers. It contains three sub workers:

Every Worker object created by JsWorker has the same API. JsWorker has shielded you from different APIs exported by different worker thread implementations.

Details of these three sub workers are listed below:

Name Supported browsers Can be created from text? Can be created from url?
Google Gears WorkerPool Those supported by Google Gears Yes Yes
Web Workers Firefox 3.1 (since beta 1), Safari 4.0 No (future) Yes
Simulated worker Any browser Yes Yes

Worker object

Functions of Worker are:

postMessage(message) is used to send a message to the scope inside a worker
terminate() is used to stop a worker.

When a worker is created, you can provide two callback functions:

onmessage is called when worker sends some messages back to the main thread.
onerror is called when any error has occurred during the execution of worker.

For more details, see API document.

Inside a worker

Code run inside a worker can use postMessage to send messages to the main thread. It also can provide a onmessage function that will be called when main thread has sent it some messages.

For more details, see API document.

Usage

Create a worker from JavaScript text

To create a worker from JavaScript text, use JsWorker.createWorkerFromText(jsText, onmessage, onerror).

Create a worker from JavaScript url

To create a worker from JavaScript url, use JsWorker.createWorkerFromUrl(jsUrl, onmessage, onerror).

Sample

This sample demonstrates how to use worker thread to calculate fibonacci numbers. More samples can be found at Samples.

Main page:

  var onmessage = function(message) {
    alert("Worker finished with result -- " + message.data);
  };
  var worker = JsWorker.createWorkerFromUrl("fib.js", onmessage);
  worker.postMessage("10");

Worker (fib.js):

function fib(n) {
	if (n < 0) {
		return;
	}
	if (n == 0 || n == 1) {
		return 1;
	}
	return fib(n - 1) + fib(n - 2);
}

onmessage = function(message) {
	var num = parseInt(message.data);
	postMessage(fib(num));
}








Hosted by Google Code