babysitter.js
A list test using Javascript coroutines
by William Dyce
HTML
<p>Hello world!</p>
<p>
Behold the babysitter :)
</p>
<ul id="myList"></ul>
JavaScript
// ----------------------------------------
// BABYSITTER MODULE
// ----------------------------------------
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.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;
}
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++;
}
}
// ----------------------------------------
// MAIN LOOP WITH DELTA-TIME CALCULATION
// ----------------------------------------
var lastFrameTime = Date.now();
function nextFrame() {
var thisFrameTime = Date.now();
var deltaTime = thisFrameTime - lastFrameTime;
lastFrameTime = thisFrameTime;
babysitter.update(deltaTime);
}
window.setInterval(nextFrame, 1000 / 60);
// ----------------------------------------
// HELPER FUNCTION BUILDING LISTS
// ----------------------------------------
function pushToList(text) {
var list = document.getElementById("myList");
var item = document.createElement("li");
var text = document.createTextNode(text);
item.appendChild(text);
list.appendChild(item);
}
// ----------------------------------------
// BABYSITTER APPLICATION
// ----------------------------------------
babysitter.add(function*(dt) {
for (var i = 0; i < 10; i++)...