Skip to content

Instantly share code, notes, and snippets.

@edtoken
Created August 22, 2018 08:30
Show Gist options
  • Save edtoken/36f935a11ceb761884a804bcbe462422 to your computer and use it in GitHub Desktop.
Save edtoken/36f935a11ceb761884a804bcbe462422 to your computer and use it in GitHub Desktop.
Example for using multiple inline web workers
const createWorker = (function(){
let workerId = 0;
function worker(){
self.onmessage = function(e){
const received = new Date()
const {type, data, created} = e.data
switch(e.data.type){
case 'join':
const result = data.join('')
const processed = new Date()
const processing = processed - received
return self.postMessage({
type,
created,
received,
processed,
processing,
result
})
}
}
}
const stringWorker = worker.toString();
const code = stringWorker.substring(stringWorker.indexOf("{")+1, stringWorker.lastIndexOf("}"));
return function(){
workerId = workerId + 1;
let onmessageCallback;
const blob = new Blob([code], {type: "application/javascript"});
const worker = new Worker(URL.createObjectURL(blob));
worker.onmessage = function(e){
if(onmessageCallback){
const accepted = new Date()
onmessageCallback({
...e.data,
accepted
})
}
}
return {
worker,
terminate: () => {
console.log(`terminate`)
worker.terminate()
},
postMessage(type, data){
worker.postMessage({type, data, created: new Date().getTime()})
},
onmessage(callback){
onmessageCallback = callback
}
}
}
})();
const w1 = createWorker()
const w2 = createWorker()
const logResponse = (name, style) => resp => {
const messages = [
`%c ${name} full processing time ${resp.accepted - resp.created}ms.`,
`%c ${name} calc time ${resp.processing}ms.`,
`%c ${name} send time ${resp.received - resp.created}ms.`,
`%c ${name} accept time time ${resp.accepted - resp.processed}ms.`,
`%c ${name} accepted ${resp.accepted.toString()}`
];
messages.forEach(message => {
console.log(message, style)
});
document.getElementById(name).innerHTML = JSON.stringify(messages, null, 2);
}
w1.onmessage(logResponse('W1', 'color: #06c'))
w2.onmessage(logResponse('W2', 'color: green'))
setTimeout(() => {
w1.terminate()
}, 10)
w1.postMessage('join', new Array(10000000).fill(0))
w2.postMessage('join', new Array(100000).fill(0))
@edtoken
Copy link
Author

edtoken commented Aug 22, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment