Skip to content

Instantly share code, notes, and snippets.

@wilbefast
Last active December 13, 2015 19:20
Show Gist options
  • Save wilbefast/3ac3735ca2dbefc7d0ba to your computer and use it in GitHub Desktop.
Save wilbefast/3ac3735ca2dbefc7d0ba to your computer and use it in GitHub Desktop.
Coroutines in Javascript
var babysitter = {
coroutines : []
}
babysitter.add = function(c)
{
// add a new coroutine to be "babysat"
babysitter.coroutines.push(c());
}
babysitter.clear = function()
{
// remove all the coroutines, start afresh
babysitter.coroutines.length = 0;
}
babysitter.countRunning = function()
{
return babysitter.coroutines.length;
}
babysitter.update = function(dt)
{
// this is where I'd really love J. Blow's 'remove' primitive...
var i = 0;
while(i < babysitter.coroutines.length)
{
var c = babysitter.coroutines[i];
// this passes delta-time to the coroutine using magic
var done = c.next(dt).done;
// remove any couroutines that have finished
if(done)
babysitter.coroutines.splice(i, 1);
else
i++;
}
}
babysitter.waitForSeconds = function*(duration_s) {
var duration_ms = duration_s * 1000;
var start_ms = Date.now();
var dt = 0;
while (Date.now() - start_ms < duration_ms)
dt = yield undefined;
return dt;
}
window.onload = function() {
var lastFrameTime = Date.now();
function nextFrame() {
var thisFrameTime = Date.now();
var deltaTime = thisFrameTime - lastFrameTime;
lastFrameTime = thisFrameTime;
babysitter.update(deltaTime);
requestAnimationFrame(nextFrame);
}
nextFrame();
babysitter.add(function*(dt) {
dt = yield undefined;
for(var i = 0; i < 10; i++)
{
dt = yield * babysitter.waitForSeconds(1.0);
console.log(i, "this frame's delta time:", dt);
}
});
}
@wilbefast
Copy link
Author

Live demo on jsfiddle :)

@grifdail
Copy link

Is this code under a specifique licence ? MIT ? CC0 ? private ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment