gated-async
Version:
Wrapper to ensure an async function runs in series when called multiple times
49 lines (48 loc) • 1.18 kB
JavaScript
// Generated by LiveScript 1.2.0
(function(){
var slice$ = [].slice;
module.exports = function(fn, opts){
var running, queue;
opts == null && (opts = {});
running = false;
queue = [];
function out(){
var args, that, timeout;
args = slice$.call(arguments);
if (running) {
queue.push([run, args]);
} else {
run.apply(null, args);
}
if ((that = opts.timeout) != null) {
timeout = setTimeout(dequeue, that);
}
function run(){
var args;
args = slice$.call(arguments);
running = true;
return fn.apply(null, slice$.call(args).concat([dequeue]));
}
function dequeue(){
var that;
if ((that = timeout) != null) {
clearTimeout(that);
}
if (that = queue.shift()) {
process.nextTick(function(){
var f, a;
f = that[0], a = that[1];
return f.apply(null, a);
});
}
return running = false;
}
return dequeue;
}
out.cancel = function(){
running = false;
return queue = [];
};
return out;
};
}).call(this);