How to run JavaScript prior to System.Web.UI.Timer OnTick?
-
22-07-2019 - |
Question
I need a client-side script to confirm that the Timer's OnTick event can proceed.
How do I invoke CanContinue() before the Timer1 postback occurs?
How do I cancel the postback if user selects Cancel?
<%@ Page Language="C#" %>
<script runat="server">
protected void Timer1_OnTick(object sender, EventArgs e)
{
Response.Write("Last Postback: " + DateTime.Now.ToString());
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Timer Test</title>
<script type="text/javascript" language="javascript">
function CanContinue() {
return confirm('The page is requesting new data. Ok or Cancel?');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Timer ID="Timer1" runat="server" OnTick="Timer1_OnTick" Interval="300000" />
</form>
</body>
</html>
NOTE: Some readers might take issue with showing a modal confirmation every x minutes. I would agree that this is poor for usability, but I'm not in a position to change the design.
UPDATE: I decided not to use a Timer after all. See this post for details on an alternative solution.
Solution 2
I decided not to use a Timer after all. See this post for details on an alternative solution.
OTHER TIPS
I don't know if there is a way to tie in to the method generated by the timer to invoke the server action. However you can gain a reference to the javascript component and start/stop or change the interval. With this in mind, you can do some nasty hacking to get the functionality you want.
For instance:
- Gain a reference to your timer. (something like:
$find(‘<%= Timer1.ClientID %>’);
) - Stop the timer.
- Create a new timer with the same interval.
- Execute your timer and cause the condition.
- Depending on the return value of your condition.. you can set the server generated timer interval to ~0 and start/stop.
This is not an elegant solution, but I can't say i've ever worked with built in asp.net timers so I can't offer too much insight.