This repository was archived by the owner on Sep 8, 2020. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathThread.js
More file actions
98 lines (85 loc) · 2.8 KB
/
Copy pathThread.js
File metadata and controls
98 lines (85 loc) · 2.8 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
* @author Joseph Evans <joeevs196@gmail.com>
* @version 1.0.0
* @since 21/08/2018
* @desc The purpose of this code is to encapsulate any form of complexity
* that one may encounter when working with web workers to allow us to
* quite literally implement multi threading features. It is a fact that
* a web worker will run in a 'background thread', as opposed to taking
* up any form of time from the main execution thread that's running.
* You may notice that this code is a little messy well that's simply
* because of the fact that it's very much a quick draft at the moment.
*
* One large purpose behind this code is to implement an alternative
* solution to writing your JavaScript code so that you can make use
* of multi threading. Personally I prefer this approach because you
* you're not required to use HTML script tags.
* @todo Consider adding support for Node.
* @todo Test.
* @todo Document in more detail.
* @todo Possibly add more features.
* @todo Possibly include more raw functionality.
* @todo General tidy up.
* @copyright 2018
*/
function Thread () {
var name, execute, update, oncomplete, data, thread;
var publicObject = {
getName: function () {
return name;
},
getCode : function () {
return execute;
},
getOnComplete : function () {
return oncomplete;
},
getData : function () {
return data;
},
getThread : function () {
return thread;
},
setName : function (n) {
name = n;
return publicObject;
},
setCode : function (code) {
var exec = code.toString();
exec = exec.substr(0, exec.lastIndexOf("}"));
exec += 'self.postMessage(arguments[0].data); \n};';
execute = exec;
return publicObject;
},
setOnComplete : function (complete) {
oncomplete = complete;
return publicObject;
},
onComplete : function (complete) {
return publicObject.setOnComplete(complete);
},
setData : function (d) {
data = d;
return publicObject;
},
start : function () {
var stringToExecute = 'self.onmessage = ' + execute.toString();
var blob = new Blob([stringToExecute], {type:"text/javascript"});
var URIObject = window.URL.createObjectURL(blob);
thread = new Worker(URIObject);
if (typeof oncomplete == 'function') { thread.onmessage = oncomplete; }
thread.postMessage(data);
return publicObject;
},
kill : function () {
try {
thread.terminate();
thread = null;
} catch (Exception) {
/* no need to worry about it */
}
return publicObject;
}
};
return publicObject;
}