Skip to content

Instantly share code, notes, and snippets.

@em
Created February 23, 2012 19:51
Show Gist options
  • Save em/1894710 to your computer and use it in GitHub Desktop.
Save em/1894710 to your computer and use it in GitHub Desktop.
tail call recursion and faux threads by timeslicing
var tcallq = [];
function utime() {
return Date.now();
}
function call2(f,t,a) {
var r = f && function() {
return f.apply(t,a);
};
return r;
}
function tcall(f,that,args) {
var lastyield = utime();
function recurse() {
while(f) {
f = f.apply(that,args) || tcallq.pop();
var t = utime();
if(f && t - lastyield > 50) {
lastyield = t;
setTimeout(recurse);
break;
}
}
}
recurse();
}
/*
function lotsOfWork(count) {
tcall(function chunk() {
console.log(count);
if(count--) return chunk;
},this);
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment