Sequential Queue Function

by HYEONGJINKIM

HTML

<div id="result"></div>

JavaScript

function myqueue(){
	var myself=this;
	var ord=[];// contains names used in promiseArr
	var funcArr=[];// contains setTimeout functions
	var me = $(document);
	
	this.add = function (func, name) {
		if (typeof funcArr[name] !== "object") funcArr[name] = [];

		funcArr[name].push(func);
		if($.inArray(name, ord)==-1){
			ord.unshift(name);
		}
		
	}

	this.call= function (name) {
		
		me.queue("deferQueue", function () {
			
			var promiseArr=[];
			
			for(func in funcArr[name]){
				promiseArr[func]=(function(){
					var dfd = new jQuery.Deferred();
					funcArr[name][func](dfd);
					return dfd.promise();	
				})();
			}
			
			$.when.apply($,promiseArr).then(function () {
				console.log("Success "+name);
				me.dequeue("deferQueue");
			}, function () {
				console.log("Fail "+name);
			});
		});
	}
	this.start = function () {
		while(ord.length>0) {
			this.call(ord.pop());
		}
		me.dequeue("deferQueue");
	}
};
myPlugin = new myqueue();
myPlugin.add(function (dfd) {
    setTimeout(function () {
        $("#result").append("<div>1</div>");
		//console.log("1");
        dfd.resolve();
    }, 2000);
}, "first");
myPlugin.add(function (dfd) {
    setTimeout(function () {
        $("#result").append("<div>1b</div>");
		//console.log("1b");
        dfd.resolve();
    }, 1000);
}, "first");
myPlugin.add(function (dfd) {
    setTimeout(function () {
        $("#result").append("<div>2</div>");
		//console.log("2");
        dfd.resolve();
    }, 1000);
}, "second");
myPlugin.add(function (dfd) {
    setTimeout(function () {
        $("#result").append("<div>3</div>");
		//console.log("3");
        dfd.reject();
    }, 500);
}, "third");
//forth will not be fired since third failed
myPlugin.add(function (dfd) {
    setTimeout(function () {
        $("#result").append("<div>4</div>");
		//console.log("4");
        dfd.resolve();
    }, 3000);
}, "forth");

myPlugin.start();