/* :: Enhanced Version @extralam :: Allows for ajax requests to be run synchronously in a queue , remove queue Usage:: var queue = new $.AjaxQueue(); // add with tag name or not , both ok queue.add('test',{ url: 'url', complete: function() { console.log('ajax completed'); }, _run: function(req) { //special pre-processor to alter the request just before it is finally executed in the queue req.url = 'changed_url' } }); // Cancel Request queue.remove('test'); */ $.AjaxQueue = function() { this.reqs = []; this.requesting = false; this.current_reqs_tag = null; this.current_req = null; }; $.AjaxQueue.prototype = { add: function(req) { //console.log("Add Request : "); this.reqs.push({n : '' , r: req }); this.next(); }, add: function(name , req) { console.log("Add Request : " + name); this.reqs.push( {n : name , r: req }); this.next(); }, remove: function (name){ if(this.current_reqs_tag == name){ console.log("Cancel Request : " + name); this.current_req.abort(); this.current_req = null; this.current_reqs_tag = null; this.requesting = false; this.next(); }else{ for (var i = 0; i < this.reqs.length; i++) { if(this.reqs[i]['n'] == name){ this.reqs.splice(i, 1); break; } } } }, next: function() { console.log(' Q Size ' + this.reqs.length); if (this.reqs.length == 0) { return; } if (this.requesting == true) { return; } var request = this.reqs.splice(0, 1)[0]; var req = request['r']; var complete = req.complete; var self = this; self.current_reqs_tag = request['n']; if (req._run) { req._run(req); } req.complete = function() { if (complete) { complete.apply(this, arguments); } self.requesting = false; self.next(); } self.requesting = true; self.current_req = $.ajax(req); } };