How to run JavaScript prior to System.Web.UI.Timer OnTick
Jan 21, 2009
The short answer: you can’t, or at least not easily, but there’s a better
way anyway.
Let’s say you have a page that needs to post back every X minutes.
In my case, I needed to develop an auto-save feature that the client
requested. Saving the data would happen server side, so I just used
a Timer
to initiate regular post backs.
The problem surfaced when they also wanted a client-side prompt to allow or
cancel the auto post back. System.Web.UI.Timer does not have any client
side events exposed, so I searched the web and asked StackOverflow
what they would do.
The only response to my post confirmed that the Timer is a bad fit.
I could hack it, but there must be a better way.
So instead of using a Timer to initiate post backs, I switched to a combination
of setTimeout() and __doPostBack(). It’s pure HTML and JavaScript, even better.
In this example, I added an update panel to demonstrate how __doPostBack()
can also be used to create a partial post back (leaving some parts of the
page unchanged after the auto post back). That’s not necessary, but if you
are posting back to the server automatically, an AJAX experience will
probably be better for the user.