Ox.queue: add 'cancel' and 'reset' (=cancel+clear) methods
This commit is contained in:
parent
7bd38b3bb9
commit
eb4808d4c1
1 changed files with 44 additions and 16 deletions
|
@ -88,37 +88,65 @@ Ox.queue <f> Queue of asynchronous function calls with cached results
|
|||
The results are cached based on all arguments to `fn`, except the last one,
|
||||
which is the callback.
|
||||
(fn, maxThreads) -> <f> Queue function
|
||||
.clear <f> Clear method
|
||||
.cancel <f> Cancels all running function calls
|
||||
.clear <f> Clears the queue
|
||||
.reset <f> Cancels all running function calls and clears the queue
|
||||
fn <f> Queued function
|
||||
maxThreads <n|10> Number of parallel function calls
|
||||
@*/
|
||||
Ox.queue = function(fn, maxThreads) {
|
||||
var maxThreads = maxThreads || 10,
|
||||
queue = [],
|
||||
processing = [],
|
||||
queued = [],
|
||||
ret = Ox.cache(function() {
|
||||
queue.push(Ox.toArray(arguments));
|
||||
var args = Ox.toArray(arguments);
|
||||
queued.push({
|
||||
args: args,
|
||||
key: getKey(args)
|
||||
});
|
||||
process();
|
||||
}, {
|
||||
async: true,
|
||||
key: function(args) {
|
||||
return JSON.stringify(args.slice(0, -1));
|
||||
}
|
||||
key: getKey
|
||||
}),
|
||||
threads = 0;
|
||||
ret.clear = function() {
|
||||
queue = [];
|
||||
ret.cancel = function() {
|
||||
processing = [];
|
||||
return ret;
|
||||
};
|
||||
ret.clear = function() {
|
||||
queued = [];
|
||||
return ret;
|
||||
};
|
||||
ret.reset = function() {
|
||||
return ret.cancel().clear();
|
||||
};
|
||||
function getKey(args) {
|
||||
return JSON.stringify(args.slice(0, -1));
|
||||
}
|
||||
function process() {
|
||||
var n = Math.min(queue.length, maxThreads - threads);
|
||||
var n = Math.min(queued.length, maxThreads - threads);
|
||||
if (n) {
|
||||
threads += n;
|
||||
Ox.parallelForEach(queue.splice(0, n), function(args, index, array, callback) {
|
||||
processing = processing.concat(queued.splice(0, n));
|
||||
Ox.parallelForEach(
|
||||
processing,
|
||||
function(value, index, array, callback) {
|
||||
var args = value.args, key = value.key;
|
||||
fn.apply(this, args.slice(0, -1).concat(function(result) {
|
||||
threads--;
|
||||
var index = Ox.indexOf(processing, function(value) {
|
||||
return value.key == key;
|
||||
});
|
||||
if (index > -1) {
|
||||
processing.splice(index, 1);
|
||||
args.slice(-1)[0](result);
|
||||
}
|
||||
threads--;
|
||||
callback();
|
||||
}));
|
||||
}, process);
|
||||
},
|
||||
process
|
||||
);
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
|
|
Loading…
Reference in a new issue