Thursday, March 31, 2011

Clock in Visualforce page

It has been a long time since my dormant mode started, finally I am back.

Well, this may not be a very peculiar requirement that you get from your client but you may find it interesting to show a countdown timer or a stop watch or even a clock on a visualforce page.

I will discuss, how to show a ticking clock in a visualforce page. The countdown timer or stop watch can be derived from this.

I have taken reference from W3Schools for the javascript. Infact, I was searching for some javascript function which does something on some specified time interval and I found two very useful javascript functions, "setInterval" and "clearInterval".

The visualforce page tag is just a container for the html and javascript.

<apex:page id="thePage" showHeader="false">

<html>
<body>
<center>
<div id="clock"></div>
</center>

<br/>
<div align="right">
<button onclick="int=window.clearInterval(int);" id="stop">Stop Clock</button>
</div>
</body>

<script type="text/javascript">
var int = self.setInterval("clock()",1000);
function clock()
{
    var d=new Date();
    var t=d.toLocaleTimeString();
    document.getElementById("clock").innerHTML = "<B>" + t + "</B>";
}
</script>

</html>

</apex:page>


You can play around with "setInterval" and "clearInterval" functions to create a stop watch or countdown timer code.

Hope this was interesting and useful.

Happy Clouding.. :)





No comments:

Post a Comment