Last active
September 10, 2015 14:14
-
-
Save ZAYEC77/36eaf5a3480c07cb9f10 to your computer and use it in GitHub Desktop.
Queue JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Queue() { | |
var self = this; | |
self.queue = []; | |
self.push = function (fn, context, params) { | |
params = params || []; | |
context = context || this; | |
self.queue.push({fn: fn, params: params, context: context}); | |
return self; | |
}; | |
self.pushFront = function (fn, context, params) { | |
params = params || []; | |
context = context || this; | |
self.queue.unshift({fn: fn, params: params, context: context}); | |
return self; | |
}; | |
function callback() { | |
if (self.queue.length > 0) { | |
var item = self.queue.pop(); | |
var args = item.params; | |
args.push(callback); | |
item.fn.apply(item.context, args); | |
}else{ | |
self.final(); | |
} | |
} | |
self.start = function (cb) { | |
self.final = cb; | |
callback(); | |
} | |
} | |
var q = new Queue(); | |
q.push(function (cb) { | |
console.log(1); | |
setTimeout(function () { | |
cb(); | |
}, 2000); | |
}, this); | |
q.push(function (cb) { | |
console.log(2); | |
setTimeout(function () { | |
cb(); | |
}, 1000); | |
}, this); | |
q.push(function (cb) { | |
console.log(3); | |
setTimeout(function () { | |
cb(); | |
}, 3000); | |
}, this); | |
q.start(function () { | |
console.log('done'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment