javascript: Command Queue

Command Queue javascript:

inspired from “Building a Javascript HTTP Request Queue” at:


 Section 10.1 “Call Tracking” from the book “Ajax Design Patterns” by Michael Mahemoff, copyright 2006.

//A queue of command objects to be executed in sequence

function commandQueue()
	//private variable queue:
	var queue = new Array();

	//Assumption:this variable (and the queue itself) is being used
	//in a single-threaded javascript environment.  Otherwise some
         //synchronization of the queue would be required for safety.
	var functor = null;//current command object assumed to support methods run() and cancel()

	var onComplete = function()
	{//callback function assumed to be called by functor when functor
         //has completed it's intended operation.  Functor's run() method
         //in turn might call asyncrhonous methods to which it could pass callback methods.
         //It should therefore use its own callbacks to track when its calls to
	//asynchronous functions are complete and in turn call this callback function
	//when that has occurred.
		functor = null;

	//private method callQueue:
	var callQueue = function()
		if((queue.length > 0) && (functor == null))
			functor = queue.shift();;

	//public method enqueue:
	//places functor (assumed to support methods run() and cancel())
	//on tail of queue such that its run() method
         //is executed when it gets shifted off the end of the queue
         //by a recurring timer event that simulates a separate thread processing
         //the queue.
	//Remember: functor assumed to support methods run() and cancel()
	this.enqueue = function(functor)

	//public method dequeue:
	//remove the functor at the head of the queue and don't execute it.
	this.dequeue = function()
		if(queue.length > 0)

	//public method clear
	this.clear = function()

	//public method cancel:
	//Calls cancel on the current functor (whose
         //run() method has been called but hasn't yet called the onComplete()callback
         //passed into its run() method.  This functor should ideally
	//call this onComplete() callback
	//in its cancel method.
	this.cancel = function()
		functor = null;

	//public method cancelAll:
	//clears queue and
	//calls cancel on current functor and
	this.cancelAll = function()
		functor = null;

	var queueWatcher = setInterval(callQueue,100);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: