Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Created June 1, 2011 14:46
Show Gist options
  • Save JamieMason/1002436 to your computer and use it in GitHub Desktop.
Save JamieMason/1002436 to your computer and use it in GitHub Desktop.
A very basic object which takes an array of functions and calls them in sequence at defined intervals. I don't imagine a lot of other uses for it, but it was used to save time on a repetitive task on a UI where I wanted to post incremental data to a form
function functionQueue (aFunctions, nSecondsInterval)
{
var _queue = [],
_arguments = [],
i,
oSelf = this;
nSecondsInterval = nSecondsInterval * 1000;
function curry(fn)
{
var curryArgs = Array.prototype.slice.call(arguments, 1);
return function()
{
var newArgs = Array.prototype.slice.call(arguments, 0),
mergedArgs = curryArgs.concat(newArgs);
return fn.apply(this, mergedArgs);
};
}
function queuedFunction(nFunctionIndex, fQueueItem, nDelayMilliseconds)
{
setTimeout(function()
{
var nNextItem = _queue[nFunctionIndex + 1];
fQueueItem.apply(oSelf, _arguments);
if (nNextItem)
{
nNextItem.apply(oSelf, _arguments);
}
},
nDelayMilliseconds);
}
for (i = 0; i < aFunctions.length; i++)
{
_queue.push(curry(queuedFunction, i, aFunctions[i], nSecondsInterval));
}
this.start = function()
{
_arguments = Array.prototype.slice.call(arguments, 0);
_queue[0](_arguments);
}
}
@JamieMason
Copy link
Author

Example usage

var myQueuedUpFunctions = new functionQueue ([
    function(){console.log('1st function', arguments[0]);},
    function(){console.log('2nd function', arguments[1]);},
    function(){console.log('3rd function', arguments[2]);}
], 1);

myQueuedUpFunctions.start('pimp','my','ride');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment