Start /Stop ASP.NET Timer Control using JavaScript

When we add a timer control to a web page it will add the following script to the page.

  1. <script type="text/javascript" >    
  2. //<![CDATA[    
  3. Sys.Application.add_init(function() {    
  4.     $create(Sys.UI._Timer, {"enabled":true,"interval":5000,"uniqueID":"Timer1"}, nullnull, $get("Timer1"));    
  5. });    
  6. //]]>    
  7. </script>  
Now in aspx page, I was refreshing page after fixed time using timer control. But the problem was that when I was performing certain actions the page would refresh and this behavior is not as expected. While performing any operations page should not refresh.

To solve this issue I stopped the timer control using JavaScript and when the task is completed again I start the timer control. In my example I will open a modal popup from Gridview and it closes after page refresh .The various methods available for timer control at client side using JavaScript are:

  • For stop timer control tick event - timer._stopTimer();
  • For start timer control tick event - timer._startTimer();
  • For change interval of timer - timer.set_interval(5000);
  • For checking whether timer is enabled - timer.get_enabled();
  • For enabling and disabling timer -timer.setenabled(true); true for enabling and false for disabling.

Below is the code used to solve this issue.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="StopTimer.aspx.cs" Inherits="StopTimer" %>    
  2.     
  3. <!DOCTYPE html>    
  4.     
  5. <html xmlns="http://www.w3.org/1999/xhtml">    
  6. <head runat="server">    
  7.     <title></title>    
  8.     
  9.   <meta charset="utf-8">    
  10.   <meta name="viewport" content="width=device-width, initial-scale=1">    
  11.   <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">    
  12.   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>    
  13.   <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>    
  14.     <script>    
  15.              
  16.         function showpopup()    
  17.         {    
  18.             var timer = $find('<%= Timer1.ClientID %>');    
  19.             timer._stopTimer();    
  20.             console.log("Timer stopped");    
  21.             $('#myModal').modal('show');    
  22.         }    
  23.         $(document).ready(function () {    
  24.             $(".custom-close").on('click', function () {    
  25.     
  26.                     
  27.                 var timer1 = $find('<%= Timer1.ClientID %>');    
  28.     
  29.                 var value = $('#<%=DropDownList1.ClientID %>').val();    
  30.                   
  31.                 timer1.set_interval(parseInt(value));    
  32.                    timer1._startTimer();      
  33.     
  34.     
  35.                 $('#myModal').modal('hide');    
  36.             }    
  37.             )    
  38.         });    
  39.     </script>    
  40. </head>    
  41. <body>    
  42.     <form id="form1" runat="server">    
  43.     <div>    
  44.     
  45.         <!-- Modal -->    
  46.   <div class="modal fade" id="myModal" role="dialog">    
  47.     <div class="modal-dialog">    
  48.         
  49.       <!-- Modal content-->    
  50.       <div class="modal-content">    
  51.         <div class="modal-header">    
  52.           <button type="button" class="custom-close" >×</button>    
  53.           <h4 class="modal-title">Modal Header</h4>    
  54.         </div>    
  55.         <div class="modal-body">    
  56.           <p>Some text in the modal.</p>    
  57.         </div>    
  58.         <div class="modal-footer">    
  59.           <button type="button" class="btn btn-default" >Close</button>    
  60.         </div>    
  61.       </div>    
  62.           
  63.     </div>    
  64.   </div>    
  65.       
  66.         <asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">    
  67.             <asp:ListItem Text="Refresh Every 5 sec" Value="5000" Selected="True"></asp:ListItem>    
  68.             <asp:ListItem Text="Refresh Every 1 Min" Value="60000" ></asp:ListItem>    
  69.             <asp:ListItem Text="Refresh Every 2 Min" Value="120000"></asp:ListItem>    
  70.             <asp:ListItem Text="Refresh Every 3 Min" Value="180000"></asp:ListItem>    
  71.         </asp:DropDownList>    
  72.         <asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick"></asp:Timer>    
  73.            
  74.                     
  75.         <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">    
  76.     
  77.             <Columns>    
  78.                 <asp:TemplateField HeaderText="Price">    
  79.                     <ItemTemplate>    
  80.                         <asp:Label ID="Label1" runat="server" CssClass="btn "  onclick="showpopup();" Text='<% #Eval("Price") %>'></asp:Label>    
  81.                     </ItemTemplate>    
  82.                 </asp:TemplateField>    
  83.                 <asp:TemplateField HeaderText="Datetransaction">    
  84.                     <ItemTemplate>    
  85.                         <asp:Label ID="Label2" runat="server" Text='<% #Eval("Datetransaction") %>'></asp:Label>    
  86.                     </ItemTemplate>    
  87.                 </asp:TemplateField>    
  88.                 <asp:TemplateField HeaderText="Productcode">    
  89.                     <ItemTemplate>    
  90.                         <asp:Label ID="Label3" runat="server" Text='<% #Eval("Productcode") %>'></asp:Label>    
  91.                     </ItemTemplate>    
  92.                 </asp:TemplateField>    
  93.             </Columns>    
  94.         </asp:GridView>    
  95.                     
  96.                 
  97.     </div>    
  98.     </form>    
  99. </body>    
  100. </html>  
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Configuration;    
  4. using System.Data.SqlClient;    
  5. using System.Linq;    
  6. using System.Web;    
  7. using System.Web.UI;    
  8. using System.Web.UI.WebControls;    
  9.     
  10. public partial class StopTimer : System.Web.UI.Page    
  11. {    
  12.     string connStr = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;    
  13.     protected void Page_Load(object sender, EventArgs e)    
  14.     {    
  15.         Timer1.Interval = Convert.ToInt32(DropDownList1.SelectedValue);    
  16.         if (!IsPostBack)    
  17.             grdibind();    
  18.     }    
  19.     protected void grdibind()    
  20.     {    
  21.         SqlConnection con = new SqlConnection(connStr);    
  22.         SqlCommand cmd = new SqlCommand();    
  23.         cmd.CommandText = "select  top 1000 * from Sales";    
  24.         cmd.Connection = con;    
  25.         con.Open();    
  26.         GridView1.DataSource = cmd.ExecuteReader();    
  27.         GridView1.DataBind();    
  28.         con.Close();    
  29.     }    
  30.     protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)    
  31.     {    
  32.         Timer1.Interval = Convert.ToInt32(DropDownList1.SelectedValue);    
  33.     }    
  34.     protected void Timer1_Tick(object sender, EventArgs e)    
  35.     {    
  36.         grdibind();    
  37.     }    
  38. }   
On Clicking any cell of the Price column a popup will open using showpopup() thereby stopping timer control using _stopTimer(). When close of Modal popup again i call _startTimer().

Next Recommended Reading Timer Control In ASP.NET