The purpose of this code is to allow to add functions to a queue, that will execute them sequentially.
With this in mind, it also allows to execute them with a defined delay, to prevent them from blocking the browser.
(function(window, undefined){
'use strict';
var queue = [];
var running = false;
var stop = false;
var log = function(data){
//some browsers may not have the .error method
(window.console.error || window.console.log).call(window.console, data);
};
var runNext = function(){
//I have to do like this, so I don't insert it back
var fn = queue[0];
setTimeout(function(){
try
{
//sometimes, when it is to stop, it's already here
if(!stop)
{
queue.shift();//remove it from the queue
fn.fn();
}
}
catch(e)
{
//simply log it, to give a chance to other functions
log(e);
}
if(queue.length && !stop)
{
setTimeout(runNext, 1);
}
else
{
running = false;
}
}, fn.delay);
};
window.FnQueue = {
add: function(fn, delay){
if(!(fn instanceof Function))
{
log('FnQueue.add - fn must be a function');
return window.FnQueue;
}
if(isNaN(delay) || delay < 1)
{
log('FnQueue.add - delay must be a number equal or higher than 1');
return window.FnQueue;
}
queue.push({
fn:fn,
delay:delay
});
//starts the execution only if it wasn't running and stopped
if(!running && !stop)
{
running = true;
setTimeout(runNext, 1);
}
return window.FnQueue;
},
clear: function(){
queue = [];
return window.FnQueue;
},
stop: function(){
stop = true;
return window.FnQueue;
},
resume: function(){
stop = false;
if(!running && queue.length)
{
setTimeout(runNext, 1);
}
return window.FnQueue;
},
getQueue: function(){
return queue;
},
isRunning: function(){
return running && !stop;
}
};
})(Function('return this')());
What can I improve on my code to make it less spaghetti-ish and more distributed? What inefficient/unnecessary code can I improve?