Last active
August 29, 2015 14:01
-
-
Save danallison/321f5d3269e3e4c3404d to your computer and use it in GitHub Desktop.
Create a Web Worker on the fly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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