-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask_queue.js
More file actions
59 lines (55 loc) · 1.96 KB
/
Copy pathtask_queue.js
File metadata and controls
59 lines (55 loc) · 1.96 KB
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
/**
* @author Jeffrey.Deng
* 将按队列执行任务
* 可以队列ajax和普通任务
*/
(function (factory) {
/* global define */
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
// Browser globals
window.TaskQueue = factory(window.jQuery);
}
})(function ($) {
/* Class: TaskQueue
* Constructor: handler
* takes a function which will be the task handler to be called,
* handler should return Deferred object(not Promise), if not it will run immediately;
* methods: append
* appends a task to the Queue. Queue will only call a task when the previous task has finished
*/
var TaskQueue = function (handler) {
var tasks = [];
// empty resolved deferred object
var deferred = $.when();
// handle the next object
function handleNextTask() {
// if the current deferred task has resolved and there are more tasks
if (deferred.state() == "resolved" && tasks.length > 0) {
// grab a task
var task = tasks.shift();
// set the deferred to be deferred returned from the handler
deferred = handler(task);
// if its not a deferred object then set it to be an empty deferred object
if (!(deferred && deferred.promise)) {
deferred = $.when();
}
// if we have tasks left then handle the next one when the current one
// is done.
if (tasks.length >= 0) {
deferred.done(handleNextTask);
}
}
}
// appends a task.
this.append = function (task) {
// add to the array
tasks.push(task);
// handle the next task
handleNextTask();
};
};
return TaskQueue;
});