Often I ask myself why it does not exist a way to control the status of a timer control on client-side. The Timer is a client-side control, incapsulated as IScriptControl into a server-control, but its use is focused in raise asyncronous postbacks without the intervention of the user. But it is simply uncontrollable. After you set its interval and enable it on server side it is impossible to stop it on the client without raise a postback.
This is a bad thing in my opinion. There was a bunch of cases when you may have the need to stop/start the timer responding to a client event. So I decided to analyze the inner working of the control to find a way to solve this issue. And here is the result of my work.
Suppose to have a Timer oin a page, side by side with a Checkbox thats need to start/stop the temporized postback. The first step is to find a reference to the client component representing the Timer.
var timer = $find('<%= timer.ClientID %>');
the $find() function simply enumerate all the components registered into the page and returns the instance to the caller. Now here is how to write an event handler for the click event of the checkbox to enable/disable the timer:
var chkEnabled = $get('chkEnabled');
chkEnabled.onclick = function()
{
var timer = $find('<%= timer.ClientID %>');
timer.set_enabled(chkEnabled.checked);
if (timer.get_enabled())
timer._startTimer();
else
timer._stopTimer();
}
You may think to have simply to set/reset the enabled property, but watching at the timer client code you may see that this property is not directly linked with the start/stop of the timer. It is only a property to acquire the value of the server control property, like always happen with the IScriptControls. So you have to manually call the _startTimer() and _stopTimer() private methods for this action to have an effect.