Auto refresh page using javascript in asp.net


Description:-

In this article we will see about how to auto refresh page using JavaScript In asp.net. Here I have create simple we application to display auto refresh with page onload in web page. Using JavaScript call the function to refresh the page in asp.net. for start the timer and stop the timer for after refreshing page. We can set time for when we want to refresh the page onload event.

Default.aspx:-

<body onload="InitializeTimer(5)">
  <form id="form1"runat="server">
  <div>
    <font>This page will be refreshed after
      <asp:Label ID="lbltime" runat="server" Style="font-weight: bold;"></asp:Label>
    </font>
    <font>seconds</font>
  </div>
  </form>
</body>

JavaScript Code:-

<script type="text/javascript" language="JavaScript">
  var secs;
  var timerID = null;
  var timerRunning = false;
  var delay = 1000;

  function InitializeTimer(seconds) {
  //Set the length of the timer, in seconds
            secs = seconds;
            StopTheClock();
            StartTheTimer();
        }

  function StopTheClock() {
  if (timerRunning)
                clearTimeout(timerID);
            timerRunning = false;
        }

  function StartTheTimer() {
  if (secs == 0) {
                StopTheClock();
  // Here's where you put something useful that's
  // supposed to happen after the allotted time.
  // For example, you could display a message:
                window.location.href = window.location.href;
                alert("Your page has been refreshed !!!!");
            }
  else {
  //self.status = 'Remaining: ' + secs;
                document.getElementById("lbltime").innerText = secs + " ";
                secs = secs - 1;
                timerRunning = true;
                timerID = self.setTimeout("StartTheTimer()", delay);
            }
        }
</script>

Default.aspx.cs:-
Or else we can set time on code behind to start timer when page load. Here is the sample code to start time on code behind.

protected void Page_Load(object sender, EventArgs e)
{
  try
  {
    lit.Text = "<script>InitializeTimer(" + 5 + ");</script>";
  }
  catch (Exception Ex)
  {
    Response.Write(System.Reflection.MethodInfo.GetCurrentMethod().Name + "-->" + Ex.Message);
  }
}

Related Posts

Previous
Next Post »

Thanks for comments.....