-
Notifications
You must be signed in to change notification settings - Fork 0
/
task-runner.js
66 lines (57 loc) · 1.41 KB
/
task-runner.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*******************************************************************************
* Task Runner Module
*******************************************************************************
* Tries to throttle some of the async madness in node. Useful script
* when debugging async issues
*
*
*/
var task_runner = module.exports;
task_runner.TaskRunner = function()
{
this.tasks = [];
this.concurrency = 0;
this.done = null;
this.maxConcurrency = 10;
this.numTasksInProgress = 0;
};
task_runner.TaskRunner.prototype = {
add: function(callback)
{
this.tasks.push(callback);
},
numTasks: function()
{
return this.tasks.length;
},
run: function(done, maxConcurrency)
{
if (this.numTasks() === 0)
{
if (done)
done();
return;
}
this.done = done || this.done;
this.maxConcurrency = maxConcurrency || this.maxConcurrency;
var target = this.tasks.length;
var that = this;
var next = function()
{
that.numTasksInProgress--;
that.concurrency--;
// (--target === 0 ? that.done() : that.run());
if (that.tasks.length === 0 && that.numTasksInProgress === 0)
that.done();
else
that.run();
};
while (this.concurrency < this.maxConcurrency && this.tasks.length > 0)
{
this.concurrency++;
var callback = this.tasks.shift();
this.numTasksInProgress++;
callback(next);
}
}
};