Skip to content

Instantly share code, notes, and snippets.

@danallison
Last active August 29, 2015 14:01
Show Gist options
  • Save danallison/321f5d3269e3e4c3404d to your computer and use it in GitHub Desktop.
Save danallison/321f5d3269e3e4c3404d to your computer and use it in GitHub Desktop.
Create a Web Worker on the fly
useWorkerToDo = (fn, data) ->
window.URL or = window.webkitURL
workerSupported = window.Worker and window.URL and window.Blob
callbacks = []
done = false
returnVal = undefined
resolve = ->
while callbacks.length
returnVal = callbacks.shift()(returnVal)
return
onmessage = (e) ->
returnVal = e.data
resolve()
done = true
return
promise = {
then: (cb) ->
callbacks.push cb
resolve() if done
return promise
}
if workerSupported
blob = new Blob(["
self.onmessage = function(e) {
self.postMessage( (#{fn.toString()})(e.data) );
};
"], { type: 'application/javascript' })
blobURL = window.URL.createObjectURL blob
worker = new Worker blobURL
worker.onmessage = onmessage
worker.postMessage data
window.URL.revokeObjectURL blobURL
else
setTimeout ->
onmessage data: fn(data)
return
, 1
return promise
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment