-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
jThread.js
53 lines (43 loc) · 1.28 KB
/
jThread.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Author: Alexander Cheprasov
// Email: alexander@cheprasov.com
(function() {
"use strict";
var jThread = window.jThread = function(workerFunction, doneFunction) {
if (this instanceof jThread) {
return jThread(workerFunction, doneFunction);
}
if (typeof(workerFunction) !== 'function' || typeof(doneFunction) !== 'function') {
throw new Error('Incorrect arguments for jThread');
}
if (!window.Worker || !window.URL || !window.URL.createObjectURL || !window.Blob ) {
//return simple async function
return function (/* args */) {
var args = Array.prototype.slice.call(arguments);
setTimeout(function() {
doneFunction(workerFunction.apply(workerFunction, args), 'timer');
}, 0);
}
}
var worker = new Worker(
window.URL.createObjectURL(
new Blob([
'self.onmessage = function(wrk) {' +
'var f = ' + Function.toString.call(workerFunction) + ';' +
'self.postMessage({status: "worker", result: f.apply(f, wrk.data.args)});' +
'};'
],
{type : 'text/javascript'}
)
)
);
worker.onmessage = function(wrk) {
doneFunction (wrk.data.result, wrk.data.status);
}
return function(/* args */) {
var obj = {
args : Array.prototype.slice.call(arguments)
};
worker.postMessage(obj);
}
}
}());