JAVASCRIPT TIMER
It was necessary when i was developing an application. The requirement was small but i got good technic if you want to show the real time in your page(jsp - servlet - html - ... whatever you use) you can use javascript inside of the associated <script> tags.
<script type="text/javascript">
//Your code
</script>
You can code your own codes into the tags as you see above. Now lets code how to show real time on your page. Lets explain : In the first div we will show the date of today then we will define a new specific date and we will show stopwatch for the remaining milliseconds, seconds, hours and days.
1 ) Firstly we should know there is function that enables you to run any of the javascript function when the page loads that is
body onload tag.
2 ) Secondly there is another usable function that you can run any of the javascript function continuesly at the time intervals which you define. That is :
setTimeout javascript function.
setInterval(function(){show()},10); that will be run after 10 ms again and again.
3 ) 1 seconds = 1000 ms, 1 min = 60 sec 1 hour = 60 minutes, 1 day = 24 hours.
The Code is below
<html>
<head>
<body onload="show()">
</head>
<body>
<div id="specifiedDay"></div>
<div id="today"></div>
<div id="milliseconds"></div>
<div id="seconds"></div>
<div id="minutes"></div>
<div id="hours"></div>
<div id="days"></div>
</body>
<script type="text/javascript">
function show()
{
var specifiedDate = new Date(2004,12,30);
document.getElementById('specifiedDay').innerHTML="Specified Date : "+specifiedDate;
var today=new Date();
document.getElementById("today").innerHTML="Today : "+today;
var difference = today.getTime()-specifiedDate.getTime();
document.getElementById('milliseconds').innerHTML="Difference Milliseconds : "+difference;
document.getElementById('seconds').innerHTML="Difference Seconds : "+Math.floor((difference/1000)%60);
document.getElementById('minutes').innerHTML="Difference Minutes : "+Math.floor((difference/(60*1000))%60);
document.getElementById('hours').innerHTML="Difference Hours : "+Math.floor((difference/(60*60*1000))%24);
document.getElementById('days').innerHTML="Difference Days"+Math.floor(difference/(1000*60*24*24));
setInterval(function(){show()},10);
}
</script>
</html>
!! This is good point if you set your javascript that you want to run without any function you should define your javascript at the bottom of the page before </html> tag after the html dom objects. Because some time may require for the loading of all the doms so any javascript code that works immediately before the finish of loading give you error that is not correct actually. Or you can use window.onload that is more reliable.
No comments:
Post a Comment