I'm studying javascript and I rewrote this code from a book:
var controller = {};
controller.queue=[];
controller.add = function (func) {
controller.queue.push(func);
};
controller.run = function () {
controller.queue.shift() (controller.run);
}
function longRunA(callback){
console.log("A");
setTimeout(callback,2000);
}
function longRunB(callback){
console.log("B");
setTimeout(callback,1000);
}
controller.add(longRunA);
controller.add(longRunB);
controller.run();
The printout is correct, A following two seconds after B, this is what he had to do.
Some things are not clear to me.
- Why does he write
controller.runin parentheses after callingcontroller.queue.shift ()? I don't understand if it is done to make the function recursive, and I don't understand the role of the round brackets surroundingcontroller.run. The console reports this problem:uncaught typeerror: controller.queue.shift (..) is not a function at controller.run controller.addis called withlongRunAargument, but I don't understand why it is correct to calllongRunAfunction without arguments. I would have removed the word callback in the function definition.