基本代码

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
function FQKTask(params) { this.params = params; }
FQKTask.prototype = {func: undefined};

function FQKTaskQueue() {
this._pendingTasks = [];
this._runningTasks = [];
}
FQKTaskQueue.prototype = {
_maxOperationCount: 1,
_pendingTasks: undefined,
_runningTasks: undefined,
isFunction: function (functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
},
setMaxOperationCount: function (count) {
if(count > 0)
{
this._maxOperationCount = Number(count);
}
},
addTask: function (task) {
if(!(task instanceof FQKTask))
{
return ;
}

if(!this.isFunction(task.func))
{
throw new Error('You must define task\'s func');
}

if(this._runningTasks.length < this._maxOperationCount)
{
this._runningTasks.push(task);
task.func(task);
}
else
{
this._pendingTasks.push(task);
}
},
removeTask: function (task) {
if(!(task instanceof FQKTask))
{
return ;
}

var index = this._runningTasks.indexOf(task);
if (index >= 0) {
this._runningTasks.splice(index, 1);
}

if(this._pendingTasks.length > 0)
{
var pendingTask = this._pendingTasks[0];
this._pendingTasks.splice(0, 1);
this.addTask(pendingTask);
}
}
};

说明及测试代码

  1. 必须实现 task.func 函数
  2. task.func 回调函数的参数为 task 本身,写作 _this
  3. task.func 函数体为需要执行的任务,一般为带回调函数的异步任务
  4. 在异步任务回调中,需要调用 taskQueue.removeTask(_this)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var taskQueue = new FQKTaskQueue();
taskQueue.setMaxOperationCount(5);

for(var i = 0; i < 10; ++i)
{
var task = new FQKTask();
task.func = function (_this) {
setTimeout(function () {
console.log(_this.index);
taskQueue.removeTask(_this);
}, 2000);
};
task.index = i;
taskQueue.addTask(task);
}