-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsimple-worker.js
More file actions
65 lines (50 loc) · 1.49 KB
/
simple-worker.js
File metadata and controls
65 lines (50 loc) · 1.49 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
"use strict";
(function() {
function isFunction(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
this.SimpleWorker = function(options) {
var func, args, handler, errHandler, runOnce
func = options['func']
if (!isFunction(func)) {
throw new Error('`func` needs to be a function.')
}
args = options['args']
handler = options['success'] || function() {}
errHandler = options['error'] || function() {}
runOnce = options['runOnce'] || false
function setupOnMessage() {
onmessage = function(e) {
if (e.data.type == '__args') {
__func.apply(this, e.data.args)
}
}
}
var funcString
funcString = 'data:text/javascript;charset=US-ASCII,var __func = ' + func.toString() + ';'
funcString += '(' + setupOnMessage.toString() + ').call(this);'
var worker = new Worker(funcString)
worker.onmessage = function(e) {
handler(e.data)
if (runOnce) worker.terminate()
}
worker.onerror = function(e) {
errHandler(e)
}
this.run = function() {
worker.postMessage({
type: '__args',
args: Array.prototype.slice.call(arguments)
})
}
this.close = function() {
worker.terminate()
}
if (args !== undefined) this.run.apply(this, args)
}
this.SimpleWorker.run = function(options) {
options['runOnce'] = true
new SimpleWorker(options)
}
}).call(this)