New Callback Queue Function

by amindunited

JavaScript

function betshopQueue(option) {
    var fn = function(){};//Function The function that will be run on each q'd item
	var qArray = [];//Array of items to be queued, or q'd if you are spelling lazily
	var running = false;//Boolean to mark while the queue is being processed
    var paused = false;//Boolean
	var parent = this;

    //An object containing the available methods
    var methods = {
        //shift the first item out of the array and run it
        proccessQueue: function() {
            
            running = true;//Flag this function as running
            
            //If there are items in the queue ... proccess them
            if (qArray.length > 0 && !paused) {
                
                //Grab the first Item from the array 
                var thisItem = qArray[0];
                
                //Must remove this item from the queue array
                qArray.shift();
                
                //Run the fn on the first array item
                fn.apply(parent, [thisItem, methods.taskComplete]);
                
            } else if (paused) {
                //console.log("program paused, run 'resume' to continue");
            } else {
                //The array is empty, we are done ... for now
                running = false;
            }
        },
        //Pause the execution loop
        pause: function(){
            //Set paused to true
            paused = true;
        },
        //Continue execution
        resume: function(){
            //Program is no longer paused, set paused to false
            paused = false;
            
            //Start running the queue again
            methods.proccessQueue();
        },
        //On complete ... run the cycle again
        taskComplete: function() {
            //Run another cycle of processing
            methods.proccessQueue();
        }
    };
    
    //When this is first created, there *should* be a function passed,
    // this will be the function that we...