Skip to content

Instantly share code, notes, and snippets.

@maxkueng
Created July 13, 2013 16:13
Show Gist options
  • Save maxkueng/5991199 to your computer and use it in GitHub Desktop.
Save maxkueng/5991199 to your computer and use it in GitHub Desktop.
readylist
var ready = require('./ready');
var cdCache = {};
function getDiskData (discId) {
cdCache[discId] = cdCache[discId] || ready(function (done) {
setTimeout(function () {
done(Math.random());
}, 2000);
});
cdCache[discId].add(function () {
console.log.call(this, arguments);
});
}
setInterval(function () {
getDiskData("10"); // 10 is a disc id
}, 500);
module.exports = ready;
function ready (get) {
var queue = [],
results,
state = 'waiting';
function completeQueue () {
while (queue.length > 0) {
queue.shift().apply(null, results);
}
}
return {
add: function (done) {
queue.push(done);
if (state === 'waiting') {
state = 'running';
get(function () {
state = 'ready';
results = arguments;
completeQueue();
});
} else if (state == 'ready') {
completeQueue();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment