I'm trying to make an webapplication where you see an Ajax countdown timer. Whenever I push a button the countdown should go back to 30 and keep counting down.
Now the problem is whenever I push the button the timer keeps counting down for a second or 2 and most of the time after that the timer keeps standing on 30 for to long.
WebForm code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="geen verbinding"></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<br />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
<asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick">
</asp:Timer>
</form>
Code Behind:
static int timer = 30;
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = timer.ToString();
}
protected void Timer1_Tick(object sender, EventArgs e)
{
timer--;
}
protected void Button1_Click(object sender, EventArgs e)
{
timer = 30;
}
Hope somebody knows what the problem is and if there is anyway to fix this.
Thanks in advance!
Why don't you implement the Timer entirely on the ClientSide? Can you explain why it has to be a callback? What does it need to do on the Server?
<script type="text/javascript" language="javascript">
var timer = 0;
function resetTimer() {
timer = 0;
timerTick();
}
function timerTick() {
var target = document.getElementById("timerResult");
target.innerHTML = timer++;
window.setTimeout("timerTick()", 1000);
}
</script>
And in the body tag...
<body onload="timerTick();">
And somewhere to display
<div id="timerResult" >timerResult</div>
You justy have to add a button chich calls resetTimer(). I'll leave that to you
Related
I am creating a page in ASP.NET Framework and I need to update text in Label every X seconds. I tried to create new Thread and call Thread.Sleep(), but it do not work, Everything what is written bellow Thread.Sleep do not execute, I do not know why. So I found on internet Timer. I created Timer and it do not call method. If I write it statically to .aspx it works:
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Timer runat="server" id="UpdateTimer" interval="5000" ontick="UpdateTimer_Tick" />
<asp:UpdatePanel runat="server" id="TimedPanel" updatemode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger controlid="UpdateTimer" eventname="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" id="DateStampLabel" />
</ContentTemplate>
</asp:UpdatePanel>
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
DateStampLabel.Text = DateTime.Now.ToString();
}
This works, but I want to change time, so I created it dynamically in C#:
if (!IsPostBack)
{
Timer timer = new Timer();
timer.Tick += UpdateTimer_Tick;
timer.Interval = 2000;
timer.Enabled = true;
}
But UpdateTimer has never been called. So I tried this and it still do not work:
protected override void OnInit(EventArgs e)
{
if (!IsPostBack)
{
Timer timeoutTimer = new Timer();
timeoutTimer.ID = "timeouttimer";
timeoutTimer.Interval = 10000;
timeoutTimer.Tick += new EventHandler<EventArgs>(UpdarteTimer_Tick);
UpdatePanel timerUpdatePanel = new UpdatePanel();
timerUpdatePanel.ContentTemplateContainer.Controls.Add(timeoutTimer);
ScriptManager.GetCurrent(this.Page).RegisterAsyncPostBackControl(timeoutTimer);
this.Page.Form.Controls.Add(timerUpdatePanel);
}
base.OnInit(e);
}
I really need this on my website. Please help me. How can I create some routine in ASP.NET? Why I can't use Thread.Sleep in website and why is my timer do not work? Thank you
If you just want to update the interval of the Timer on Page.. you can just reference the one already created and set the Interval in either Page_Init or Page_Load like this ...
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Timer runat="server" id="UpdateTimer" interval="5000" ontick="UpdateTimer_Tick" />
<asp:UpdatePanel runat="server" id="TimedPanel" updatemode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger controlid="UpdateTimer" eventname="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" id="DateStampLabel" />
</ContentTemplate>
</asp:UpdatePanel>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
UpdateTimer.Interval = 2000;
}
}
If it's ok, you can use js code
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<script type="text/javascript">
$(document).ready(function () {
setInterval(function () {
WebForm_GetElementById("MainContent_Label1").textContent = new Date().toLocaleString();
}, 1000);
});
</script>
Pay attention that Label ID and element name which you are looking for are different! (Honestly, I don't know why ASP.NET changes that ID)
After setting timer properties you have to call this line to start the timer:
timer.Start();
UPD:
I checked your UI timer and It works but It reload page every time when tick event happens.
<asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick"></asp:Timer>
and in the code behind file:
protected void Page_Load(object sender, EventArgs e)
{
Timer1.Interval = 1000;
}
protected void Timer1_Tick(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToString();
}
Thus, I recommend using js method which I mentioned in another answer.
This is just the sample code which I am trying to achieve and it cannot be performed by Javascript.
Used an Updatepanel and trying to update the progress bar that it shows the progress while function is in execution
But when doing this, updatepanel starts from zero when it is refreshed
(It's not smooth continuous transition, rather it starts from zero and reaches to specified point everytime when timer-tick event occurs)
ASPX
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:Timer runat="server" ID="Timer1" Interval="1000" Enabled="False"
ontick="Timer1_Tick" />
<br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<br />
<br />
<div id="div3" runat="server" class="progress progress-danger progress-striped progress progress_sm active " style="width: 100%;">
<div id="e3" class="bar" runat="server" role="progressbar">
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
JavaScript
var percentage;
function updateProgress2(percentage) {
var $bar1 = $("#e3");
//var $bar1 = $('.bar');
var pp = percentage + "%";
$bar1.width(pp);
$bar1.text(pp + "%");
}
C#
static int count2, i;
protected void Button1_Click(object sender, EventArgs e)
{
i=0;
count2=20;
Button1.Enabled = false;
Timer1.Enabled = true;
}
protected void Timer1_Tick(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "lol", "updateProgress2('" + count2 + "')", true);
i++;
count2 += 10;
if (count2 == 90)
{
Timer1.Enabled = false;
Button1.Enabled = true;
}
}
i want see your 'count2' property.
i can use this 'count2' property with session.
this code work correctly.
private int count2
{
get
{
if (Session["count2"] == null)
Session["count2"] = 0;
return int.Parse(Session["count2"].ToString());
}
set
{
Session["count2"] = value;
}
}
There is a simple code in which I added a timer and generated tick event but the event is not firing.
<asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick" Enabled="True" EnableViewState="True" ViewStateMode="Inherit" ClientIDMode="Inherit"></asp:Timer>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
setImageurl();
//Timer1.Tick += new EventHandler(Timer1_Tick);
//Timer1.Interval = 1000;
}
}
void setImageurl()
{
Random _rand = new Random();
int i = _rand.Next(1, 4);
Image1.ImageUrl = "~/ImagesSlideshow/" + i.ToString() + ".jpg";
}
protected void Timer1_Tick(object sender, EventArgs e)
{
setImageurl();
}
I dont know why this is happening. Help me out.
Set EnableCdn="true" on the ScriptManager and it will work, just tried it on my side:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnableCdn="true"></asp:ScriptManager>
<asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick" Interval="1000"></asp:Timer>
<asp:Image ID="Image1" runat="server" />
</form>
As a general rule of thumb you have to set Timer1.Enabled=true for a Timer control to fire it's Tick() event.
i wanted to use a timer in a program i'm working on, but it always stops after 1 tick !! can you give me any tips to make it repeat unstoppably (or until i want it to) please ??
this is my code:
int i = 20;
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "(20)";
}
protected void Timer1_Tick(object sender, EventArgs e)
{
i--;
Label1.Text = "(" + i + ")";
if (i == 0)
{
Session["Profession"] = "Visiteur";
Response.Redirect("Acceuil.aspx");
}
Edit: my HTML code :
<form id="form1" runat="server">
<div><center>
<span class="style1">message</span><br
class="style1" />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick" >
</asp:Timer>
<asp:Timer ID="Timer2" runat="server" Interval="1000">
</asp:Timer>
<br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="Label1" runat="server"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
<asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click"
PostBackUrl="~/Acceuil.aspx">Retour</asp:LinkButton>
<br />
</center>
</div>
</form>
Edit2: what i want to do is the normal redirecting code, count to 20 and refreshing every second (to show to user how much secs left) and at the end it redirects to a new page, but it wasn't working, so i was wondering why ??
and i think i got my answer from #Andrei Rînea, and thank you everyone for your help : )
Edit3: Solved and here is the code :
static int i = 20;
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
Label1.Text = "20";
}
protected void Timer1_Tick(object sender, EventArgs e)
{
i--;
Label1.Text = i.ToString();
if (i == 0)
{
i = 20;
Session["Profession"] = "Visiteur";
Response.Redirect("Acceuil.aspx");
}
}
Thanks everyone again : )
Please use the following code :
static int i = 20;
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
Label1.Text = "(20)";
}
protected void Timer1_Tick(object sender, EventArgs e)
{
i--;
Label1.Text =i.ToString();
if (i == 0)
{
Session["Profession"] = "Visiteur";
Response.Redirect("Acceuil.aspx");
}
}
your HTML code should be like :
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Timer ID="Timer1" runat="server" ontick="Timer1_Tick" Interval="1000">
</asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
I'm going to assume here that you are wishing to have a process that ticks away on your server in the background.
I'm also going to assume you've tried to add this to your Webform.
If so, the issue you have encountered, is that your Webform object only exists for the short time that it is processing your request, after which it is disposed of - including your timer.
If I'm correct, you'd probably like to take a look at Quartz.Net:
http://www.mikesdotnetting.com/article/254/scheduled-tasks-in-asp-net-with-quartz-net
You are trying to run client side code on the server. You need to do this in JavaScript instead.
The C# code will be run just before rendering the page and not longer. You probably believe the code will run as long as the visitor is on the page which is not the case.
I'm designing small instant messenger app on .NET platform.
I have a ListBox, TextBox and Button (called Send).
When user click send button, Text of TextBox will be appeared on ListBox but user should not send 3 messages in 1 minute(message restriction) and also his/her size of message should consist min 20 max 140 strings.
How can I do this?
The example below uses the timer control, if you would like to learn more about using timers in ASP.NET have a look at this video tutorial by Joe Stagner.
Basically I'm storing the number of messages in ViewState and when that number reaches 3 I start the timer which will reset the ViewState["Messages"] back to 0 after 1 minute (60 000 milliseconds) and the user is once again able to send more messages.
ASPX:
<asp:ScriptManager ID="Scriptmanager" runat="server" />
<asp:Timer ID="timer" runat="server" Enabled="false" Interval="60000" OnTick="Tick" />
<asp:UpdatePanel ID="updatePanel" runat="server">
<ContentTemplate>
<asp:TextBox MaxLength="140" ID="txtMessage" runat="server" />
<asp:Button ID="btnSend" runat="server" Text="Send" OnClick="Send" /> <span
id="error" runat="server" style="color: Red;" />
<br />
<asp:ListBox ID="lbMessages" runat="server" Width="240" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="timer" />
</Triggers>
</asp:UpdatePanel>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
ViewState["Messages"] = 0;
}
public void Send(object sender, EventArgs e)
{
error.InnerHtml = string.Empty;
string message = txtMessage.Text;
if (message.Length < 20)
{
error.InnerHtml = "The message should be at least 20 characters long";
return;
}
int messageNumber = (int)ViewState["Messages"];
if (messageNumber < 3)
{
lbMessages.Items.Add(message);
ViewState["Messages"] = ++messageNumber;
if (messageNumber.Equals(3))
timer.Enabled = true;
}
}
protected void Tick(object sender, EventArgs e)
{
ViewState["Messages"] = 0;
timer.Enabled = false;
}
Also you don't need to check for maximum length in code, there is a property for that on the textbox - MaxLength
Maybe you can set an hidden field in your page load to store serialised three last requests time and another for last minute message count.
in the click button event get text of the textbox apply your size restriction and verify message count.