Pixelbox

Welcome to Pixelbox. Friday the 5 of September 2008

Skip to content >>

An Ajax.Periodical Updater that you can turn off!

At work recently I came across an instance where I wanted to turn a script.aculo.us Ajax.Periodical Updater on and off.

After looking on the wiki it appeared that there was no way to turn the thing off once you had started it other than reloading the page. You could for example want to turn it off after an hour or when a user clicks a button.

So I came up with this code which uses a normal updater which on complete waits for a set amount of time before calling another function. This function checks a global variable to see if the updater is on or off and depending on the outcome either updates again or does nothing (stops it).

The code is below and also includes some Hijax to convert a normal link into our toggle button.


var global_updater_status = 'on';

function apply_toggle_updater() {
	// In your HTML you need a button or anchor like; Toggle Updater with the id relating to below
	// You also need to run this function onload
	if( document.getElementById('toggle_updater') ){
		var theButton = document.getElementById('toggle_updater');
		theButton.onclick = 	function(){ 
										toggle_updater(); return false;
									};
	}		
}

function toggle_updater(){
	if(global_updater_status == 'on'){
		global_updater_status = 'off';
	}else{
		global_updater_status = 'on';
		Updater();
	}
}

function Updater() {
	var url = 'ajaxGetStatus.php';
	var pars = "id=8";
	var target = "status";
	var myAjax = new Ajax.Updater(target, url, {method: 'get', parameters: pars, asynchronous:true, evalScripts:true, onComplete:function() { setTimeout('Periodical()',2000); } });
	// This one updates every 2 seconds as long as the global variable is set to on
}

function Periodical(){
	if(global_updater_status == 'on'){
		Updater();
	}
}

Hope this helps!

3 comments

Why not leave your own!

  1. hi, thanks for the code... as a hobbyist coder i wasn't sure what to do with 'myAjax' to have it execute, so i altered it and got it to work. the question i have now is if there is any way to have the div refresh at an interval of 1 as opposed to 2? i tried using Ajax.PeriodicalUpdater, but it seems to only start the process and not stop.
  2. i figured it out: setTimeout('Periodical()',2000) change to: setTimeout('Periodical()',1000) on a sidenote i would suggest changing: var global_updater_status = 'on'; to var global_updater_status = 'off'; generates more natural behaviour :)
  3. To turn a Ajax.Periodical Updater off you have to set its onComplete to undefined then call stop(); Hope that helps... Dk0

Add your own comment