Hello I am trying to implement a timer in c sharp that counts seconds and display it on my html page. But when i pass the variable to javascript it is always 0. I have searched everywhere for an answer.
This is my code so far:
The timer object:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Timers;
/// <summary>
/// Summary description for Class1
/// </summary>
public class TimerEu
{
private Timer t;
private int time;
public TimerEu()
{
this.t = new Timer(1000);
this.time = 0;
t.Elapsed += new ElapsedEventHandler(RunEvent);
t.Interval = 1000;
t.Enabled = true;
}
public void RunEvent(object source, ElapsedEventArgs e)
{
this.time++;
Console.WriteLine(time);
}
public int getTime()
{
return this.time;
}
}
aspx.cs page:
public partial class _Default : System.Web.UI.Page
{
public String[] var=new String[10];
public TimerEu time;
public int testint;
protected void Page_Load(object sender, EventArgs e)
{
time = new TimerEu();
testint = 0;
Console.Write("hello"+time.getTime());
for (int i = 0; i < 10; i++)
var[i] =Operations.test.convertString();
}
public void plus()
{
this.testint++;
}
}
and the html/javascript part:
<form id="form1" runat="server">
<div>
<br></br>
<br></br>
<br></br>
<p id="demo" runat="server"></p>
<script>
var now=0;
var x= setInterval(function () {
//now++;
now = <%=time.getTime()%>
// now =<%=testint%>
// <%plus();%>
document.getElementById("demo").innerHTML = now;
},1000)
</script>
The problem is that the javascript dosen't seem to call the getTime function every sec, instead it only gets 0 as output. What am I doing wrong?
You have to understand important thing. This statement <%=time.getTime()%>
is executed only once on the server side before rendered html page is sent to the browser. When it's executed, it will be replaced with 0
(the result of method call).
Browser will see only now = 0
and in this case, javascript code doesn't make any sense
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
var before_loadtime = new Date().getTime();
window.onload = Pageloadtime;
function Pageloadtime() {
var aftr_loadtime = new Date().getTime();
// Time calculating in seconds
pgloadtime = (aftr_loadtime - before_loadtime) / 1000
document.getElementById("loadtime").innerHTML = "Pgae load time is <font color='red'><b>" + pgloadtime + "</b></font> Seconds";
}
</script>
</head>
<body>
<h3 style="font-weight: bold; font-style: italic; font-size: large; color: #3333CC">Page load time in JavaScript</h3>
<div>
<span id="loadtime"></span>
</div>
</body>
</html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.