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!