Javascript method priority queue
Problem Statement:
There are times when people are faced with the problem of calling methods in a particular order based on some kind of priority. There are times when you wish to be able to add methods to some kind of a method queue along with the priority. The priority decides which methods is to be called first. Then at some later point, you wish to execute the methods in the queue in order of priority.
A case in point may be when you have multiple document ready handlers which add method calls to the queue, and then on the window.load event you execute all the methods.
So keeping the queue thing in mind I have come up with a solution to this problem.
Implementation:
Function_queue = new function() { // lower priority value means function should be called first var func_queue; var sort_queue = function(a, b) { if( a.priority < b.priority ) return -1; else if( a.priority == b.priority ) return 0; else return 1; } return { init : function() { func_queue = new Array(); }, /* * @param function func This can be a function name or a function itself * @param array|null args This should always be an array of args or a * null if the function accepts no arguments * @param int priority This is a zero based number, with the smaller * value meaning high priority. Function with a priority of 0 will * be executed before a funcion with priority of 2 */ add_to_queue : function(func, args, priority) { func_queue.push({ method : func, args : args, priority : priority }); }, execute_queue : function() { func_queue.sort( sort_queue ); for( var i in func_queue ) func_queue[i].method.apply( null, args ); } } }();
Usage:
(function($) { // initialize the queue Function_queue.init(); $( document ).ready(function() { // add a function to queue that does not accept any parameters Function_queue.add_to_queue(function() { alert( 'Hello World 1' ); }, null, 2); }); $( document ).ready(function() { // add another method to queue that accepts two integers as parameters Function_queue.add_to_queue(function(a, b) { alert( 'Sum = ' + ( a + b ) ); }, new Array( 3, 4 ), 1); }); $( window ).load(function() { // now all you have to do is execute the queue which will do all the magic Function_queue.execute_queue(); }); })(jQuery);
You may download the script from here.