Created
February 23, 2012 19:51
-
-
Save em/1894710 to your computer and use it in GitHub Desktop.
tail call recursion and faux threads by timeslicing
This file contains hidden or 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
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