Oct
17
2006
Ajax.NET part 2
Posted by admin under
Ajax
Here we continue our Ajax.NET exploring adventures started here .
Now lets create a page which does the same (but without image) - and also automatically reloads the time cell every 10 seconds.

While it might say somwthing about me as a person - or at least about my definition of fun :) - but it was actually fun to just sit for a minute or so and see the cell for current minute suddenly change (blinking three times when that happen). Fascinating, no flicker at all. Yes I admit, I am a nerd, but this is indeed fascinating!
Anyway, lets see what the changes are:
New page, sample2.aspx. Deleted the image and removed Hide, Show functions. In code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(sample2));
lblMinute.Text = DateTime.Now.Minute.ToString();
}
}
[AjaxPro.AjaxMethod]
public int GetCurrentMinute()
{
System.Threading.Thread.Sleep(2000);
return DateTime.Now.Minute;
}
And Javascripts were modified like this:
<script type="text/javascript">
function blink_show(sId)
{
if (document.getElementById)
document.getElementById(sId).style.visibility = "visible";
}
// blink "off" state
function blink_hide(sId)
{
if (document.getElementById)
document.getElementById(sId).style.visibility = "hidden";
}
function blink_Blink3Seconds(sId)
{
for(var i=0; i < 2700; i=i+900)
{
setTimeout("blink_hide('" + sId+"')",i);
setTimeout("blink_show('"+ sId+"')",i+450);
}
}
function MyUpdate()
{
sample2.GetCurrentMinute(MyUpdate_Callback);
}
function MyUpdate_Callback(res)
{
var lblMinute = document.getElementById("lblMinute");
var newval = res.value;
if ( lblMinute.innerHTML != newval )
{
lblMinute.innerHTML = newval;
blink_Blink3Seconds("lblMinute");
}
//10 seconds a 1000 ms
setTimeout(MyUpdate,10 * 1000);
}
//First time
//10 seconds a 1000 ms
setTimeout(MyUpdate,10 * 1000);
</script>
The secret is that we out of any function scope (last row) calls setTimeout - and therefore tells the browser to call the function MyUpdate in 10 seconds from now.
And in the callback - we do the same again.
Attachments