I have a small C# code behind to refresh a webform page (form.aspx) after 15 seconds as below:
lblMessage.Text = "<b><h2>Thank you!</h2></b></br>We will be right with you.<br><br><br>(This page will be refreshed automatically after 15 seconds)";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Success!", "setInterval(function(){location.href='/form.aspx';},15000);", true);
Right now the page will be refreshed after 15 seconds. How do I also make the timer count down every second? i.e., 15 => 14 => 13 => ... 1 then refresh so it will be better for users, they will know what is going on with the page...
"<b><h2>Thank you!</h2></b></br>We will be right with you.<br><br><br>(This page will be refreshed automatically after <span id='counter'>15</span> seconds)"
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Success!", "setTimeout(function(){location.href='/form.aspx';},15000); counter = 15; setInterval(function(){counter--; document.getElementById('counter').innerHTML = counter;},1000);", true);
Should do it.
If added a span
with id
counter
around the refresh message number.
Then I added counter = 15;
to initialize a default value of 15. And another setInterval
to the script block firing every second. With each pass it subtracts one from counter
and updates the span
with the new counter value. Users should now see the page counting down. I also changed the first setInterval
to setTimout
, since it's technically a timeout and not an interval that should occur every 15 seconds.