Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<script src="renderer.js"></script>
var worker = new Worker('worker.js');
worker.addEventListener('message', function (event) {
var message = event.data;
console.group('Message Received');
console.log( message );
console.groupEnd();
}, false);
// TEST VALID JSON ARG
worker.postMessage({
'renderer-process': 'Hello Worker Process'
});
// TEST OBJECT ARG
worker.postMessage({
rendererProcess: 'Hello Worker Process',
resultOf: (function () {
return 'the result';
})()
});
// TEST ANOTHER THREAD SAFE OBJECT ARG
var obj = new Object();
obj.isArray = [ 1,2,3,4,5 ];
obj.isString = 'Foo bar baz',
obj.resultOf = (function () {
return 'returned from self executing function';
})();
worker.postMessage(obj);
// TEST STRING ARG
worker.postMessage('Hello Worker Process');
// TEST ARRAY ARG
worker.postMessage([ 1, 2, 3, 4 ]);
// TEST BOOLEAN ARG
worker.postMessage(false);
// TEST BOOLEAN ARG
worker.postMessage(true);
// Results
Message Received
Object
renderer-process: "Hello Worker Process"
worker-process: "Hello Renderer Process"
__proto__: Object
Message Received
Object
rendererProcess: "Hello Worker Process"
resultOf: "the result"
worker-process: "Hello Renderer Process"
__proto__: Object
Message Received
Object
isArray: Array (5)
0: 1
1: 2
2: 3
3: 4
4: 5
length: 5
isString: "Foo bar baz"
resultOf: "returned from self executing function"
worker-process: "Hello Renderer Process"
Message Received
Hello Worker Process, Hello Renderer Process
Message Received
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Message Received
boolean: false
Message Received
boolean: true
self.addEventListener('message', function (event) {
var message = event.data;
// IF BOOLEAN
if ( typeof message === 'boolean' ) {
message = 'boolean: ' + message.toString();
}
// ALL OTHER MESSAGE TYPES
else {
// IF STRING OR ARRAY
if ( message.length ) {
// IF STRING
if ( typeof message == 'string' ) {
message += ', Hello Renderer Process';
}
else {
var len = message.length + 1,
floor = len,
ceil = floor * 2;
for ( ; floor < ceil; floor++ ) {
message.push(floor);
}
}
}
// IF OBJECT
else {
message['worker-process'] = 'Hello Renderer Process';
}
}
this.postMessage(message);
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment