Skip to content

Instantly share code, notes, and snippets.

@afterburn
Last active November 2, 2018 15:16
Show Gist options
  • Save afterburn/65acf4be9edd85a2c4831264318ea50b to your computer and use it in GitHub Desktop.
Save afterburn/65acf4be9edd85a2c4831264318ea50b to your computer and use it in GitHub Desktop.
Inline web worker
const worker = new InlineWorker((data) => {
postMessage(data.a + data.b)
})
worker.start({ a: 1, b: 2 }, (result) => {
console.log(result) // output: 3
})
worker.start({ a: 1, b: 2 })
.then((result) => console.log(result))
.catch((err) => console.error(err))
class WebWorker {
constructor (code) {
code = `onmessage = (e) => (${code.toString()})(e.data)`
this.blob = window.URL.createObjectURL(new window.Blob([code], { type: 'application/javascript' }))
}
start (initialData, callback) {
if (typeof callback === 'function') {
this.worker = new window.Worker(this.blob)
this.worker.onmessage = (e) => callback(e.data)
this.worker.postMessage(initialData)
} else {
return new Promise((resolve, reject) => {
try {
this.worker = new window.Worker(this.blob)
this.worker.onmessage = (e) => resolve(e.data)
this.worker.postMessage(initialData)
} catch (ex) {
reject(ex)
}
})
}
}
terminate () {
this.worker.terminate()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment