Created
February 15, 2015 04:30
-
-
Save kirbysayshi/190b17329defe007d3f1 to your computer and use it in GitHub Desktop.
A Task Queue, because sometimes I don't want to learn another API
This file contains 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 tasks = new TaskQueue(5); | |
tasks.queue(getUrl.bind(null, 'google.com')) | |
tasks.queue(getUrl.bind(null, 'yahoo.com')) | |
tasks.queue(getUrl.bind(null, 'facebook.com')) | |
tasks.next() // kick it. | |
function getUrl(url, cb) { | |
magicalXHR(url, cb); | |
} |
This file contains 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
function TaskQueue(concurrency) { | |
var _queue = []; | |
var _concurrents = 0; | |
var ctr = { | |
queue: function(fn) { | |
_queue.push(fn) | |
}, | |
next: function() { | |
while (_concurrents < concurrency) { | |
_concurrents += 1; | |
var t = _queue.shift(); | |
if (!t) return; | |
t(function() { | |
_concurrents -= 1; | |
ctr.next(); | |
}); | |
} | |
} | |
} | |
return ctr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment