/* to use the qControl object, initialize an instance of the class in this way: myQ = new qControl(); to add a single function to the queue: myFunction = function (){ code...}; myQ.addJobs(myFunction); multiple functions can be added simultaneously, just pass an array of them to .addJobs jobs are canceled by sending the appropriate job Id's to the .cancelJobs method: myQ.cancelJobs([jobID1, jobID2, jobID3]); single jobs can also be canceled the queue can be paused and unpaused with: myQ.pause(); myQ.unpause(); the qControl object is reset (initial state) with: myQ.clear(); all functions passed as jobs to the q should finish with myQ.finishJob(); for ajax functions, this should be the last line of the callback function if data is to be preserved between jobs, the .jobData object provides space in which to store such data in any desired format */ // defining the qControl object function qControl(){ // %%%%%%%%%%%%%%%% properties // .jobs is an array, each element is an object with two // properties: a jobid and a function to run this.jobs = []; this.state = "ready"; // ready, busy, paused // .jobData holds the data passed through between jobs this.jobData = {}; // %%%%%%%%%%%%%%% queries this.getCurrentJobID = function(){ var currentJobID = ""; if (this.jobs.length > 0){ currentJobID = this.jobs[0].jobID; } return currentJobID; }; this.getNextJobID = function(){ var nextJobID = ""; if (this.jobs.length > 1){ nextJobID = this.jobs[1].jobID; } return nextJobID; }; this.getState = function(){ return this.state; }; this.getQPosition = function(jobID){ var qPosition = -1; for (var i=0; i 0){ this.jobs.splice(qPosition,1); } } }; this.finishJob = function(){ var deadJob = this.jobs.shift(); this.interrupt(); if (this.state != "paused"){ this.state = "ready"; this.startNextJob(); }; }; this.startNextJob = function(){ if (this.jobs.length > 0 && this.state == "ready"){ this.state = "busy"; var jobFunction = this.jobs[0].jobFunction; if (typeof(jobFunction) === "function"){ jobFunction(); } else{ this.finishJob(); }; }; }; this.clear = function(){ this.jobs = []; this.state = "ready"; this.jobData = {}; }; this.pause = function(){ this.state = "paused"; }; this.unpause = function(){ this.state = "ready"; this.startNextJob; } // %%%%%%%%%%%%%%%%%%%% internals this.generateJobID = function(){ var newJobID = ""; var digit; for (var i=0; i<10; ++i){ digit = Math.floor(Math.random()*11); newJobID = newJobID + digit; } return newJobID; }; this.interrupt = function(){ // this function called between each job }; }