Project WolverineBroadcasting LIVE from the orbiting command centre

Every so often, you need to trigger different events on the same page. In my case, every couple of seconds I wanted to check the number of items in a queue, and maybe once a minute I wanted to update the average number of items overall.

I could just get all the information in one AJAX request, but the average number calculation was moderately intensive, and I didn’t want to bombard the server with a query that didn’t need to be done more than once a minute or so.

A (very) quick check of teh Internets didn’t reveal anything useful, and jQuery doesn’t support timers without a plugin, so I wrote my own class.

It’s very simple:

/***
 * Timer logic starts
 */
function timer_object(){
	this.create_timer=function create_timer(wait_time, callback){
		_timer(wait_time, callback);
	};
}

function _timer(wait_time, callback){
	callback();
	setTimeout('_timer(' + wait_time + ', ' + callback + ')', wait_time);
}

/***
 * Timer logic ends
 */

To use this, just use a function like this:

function getItems(){
        //Timer number one:
	var times=new timer_object();
	times.create_timer(10000, getAverage);
        //Timer number two:
	var tickets=new timer_object();
	tickets.create_timer(5000, getWaitingItems);
}

function getAverage(){
	//Ajax query to pass to the database....
}

function getWaitingItems(){
	//Ajax query to pass to the database...
}

The parameters are very simple.

tickets.create_timer(TIME_IN_MILLISECONDS, FUNCTION_TO_CALL);

TIME_IN_MILLISECONDS is a number, like 5000, while FUNCTION_TO_CALL is the function name you want to to run every 5000 seconds. Don’t include the brackets in this parameter – ie, just the name.

That’s it! You can get tricky by extending this to only fire once, or limit it to x number of times.

This entry was posted in Project Wolverine. Bookmark the permalink.

Comments are closed.

Browse by Topic