Skip to content

Instantly share code, notes, and snippets.

@aheinze
Last active February 25, 2016 16:05
Show Gist options
  • Save aheinze/2072446828a4266d858f to your computer and use it in GitHub Desktop.
Save aheinze/2072446828a4266d858f to your computer and use it in GitHub Desktop.
Execute async function
/**
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