没有任何数据可供显示
开源项目社区 | 当前位置 : |
|
www.trustie.net/open_source_projects | 主页 > 开源项目社区 > jsworker |
jsworker
|
0 | 0 | 10 |
贡献者 | 讨论 | 代码提交 |
JsWorker is a small JavaScript library that wraps current implementations of worker thread in browsers. It contains three sub workers:
Google Gears WorkerPool Web Workers Simulated worker thread using window.setTimeout 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 objectFunctions of Worker are:
postMessage postMessage(message) is used to send a message to the scope inside a worker
terminate terminate() is used to stop a worker.
When a worker is created, you can provide two callback functions:
onmessage onmessage is called when worker sends some messages back to the main thread.
onerror onerror is called when any error has occurred during the execution of worker.
For more details, see API document.
Inside a workerCode 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.
UsageCreate a worker from JavaScript textTo create a worker from JavaScript text, use JsWorker.createWorkerFromText(jsText, onmessage, onerror).
Create a worker from JavaScript urlTo create a worker from JavaScript url, use JsWorker.createWorkerFromUrl(jsUrl, onmessage, onerror).
SampleThis 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));
}