Last active
February 25, 2016 16:05
-
-
Save aheinze/2072446828a4266d858f to your computer and use it in GitHub Desktop.
Execute async function
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
/** | |
asyncexec(function(times){ | |
for (var x=0, y;x<times;x++) { | |
y = x/2; | |
} | |
release(x); | |
}, 5000000000).then(function(x) { | |
alert('Done, iterations: '+x) | |
}) | |
**/ | |
var asyncexec = function(fn, data) { | |
var canceled = false, p = new Promise(function(r, f) { | |
var w = new Worker(URL.createObjectURL(new Blob([ | |
[ | |
'self.onmessage=function(e){', | |
'var release = function(result) { self.postMessage(result) }', | |
'var result = ('+fn.toString()+')(e.data, e)', | |
'if(result!==undefined) release(result);', | |
'}' | |
].join("\n") | |
], { type: 'application/javascript' }))); | |
w.onmessage = function(e) { | |
if(!canceled) r(e.data || null, e); | |
w = null; | |
}; | |
w.onerror = function(e) { | |
if(!canceled) f(e); | |
w = null; | |
}; | |
w.postMessage(data); | |
}); | |
p.cancel = function() { | |
canceled = true; | |
}; | |
return p; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment