PDA

View Full Version : refresh time js



magik
12-22-2008, 05:46 AM
I am aiming at having a time (in a function) that refreshes itself every 10 seconds using JS but am having trouble. The time is shown but doesn't update. The page seems to be refreshing though.

Here is my code


<script type="text/javascript">
function theTime() {
var date = new Date;
var hours = date.getHours();
var minutes = date.getMinutes();
if(hours > 11){
var ext = "PM";
} else {
var ext = "AM";
}
if (hours > 12) {
hours = hours - 12;
}
if (minutes < 10){
minutes = "0" + minutes;
}
document.write(hours + ":" + minutes + ext)
}
function refreshPage(refresh)
{
setTimeout('theTime();',refresh)
}
refreshPage(10000);
</script>

Help much appreciated.
magik

Nile
12-22-2008, 06:19 AM
This should do it:


<script type="text/javascript">
var timein = function() {
var date = new Date()
var month = date.getMonth()+1;
var hours = date.getHours();
var ext;
if(hours > 12){
hours-=12;
}
if(hours == 0) hours = 12;
if(hours > 11){
ext = "PM";
} else {
ext = "AM";
}
var dateout = hours+":"+date.getSeconds()+ext;
document.getElementById('dt').innerHTML=dateout;
}
setInterval("timein()",10000);
window.onload = function () { timein(); };
</script>
<div id="dt"></div>

Twey
12-22-2008, 06:23 AM
<script type="text/javascript">
Number.prototype.pad = function(n) {
return (new Array(1 + n - this.toString().length)).join("0") + this;
};

Date.prototype.getTwelveHourStamp = function() {
var hours = this.getHours(),
mins = this.getMinutes().pad(2),
ext = hours >= 12 ? "PM" : "AM";

return (hours % 12) + ":" + mins + ext;
};

setInterval((function(f) { f(); return f; })
(function() { document.getElementById("clock").firstChild.nodeValue = (new Date()).getTwelveHourStamp(); }), 10000);
</script>Have an element somewhere to catch it:
<span id="clock">&nbsp;</span>Place the Javascript code after the element.

Nile: try to avoid innerHTML, it's non-standard and leads to horrible code if used in large quantities. Additionally, eval() (which is what happens behind the scenes just about wherever you see a string of Javascript code) is very slow and leads to most of the same problems. Please read my list of common coding mistakes (http://dynamicdrive.com/forums/showpost.php?p=158839&postcount=1337) and the links therein.
setInterval("timein()",10000);
window.onload = function () { timein(); };The former would be better written as setInterval(timein, 10000), the latter as onload = timein.

Nile
12-22-2008, 06:36 AM
Ok, thanks! I'll read your mistakes list and keep your tips in mind, also here:


Date.prototype.getTwelveHourStamp = function() {
var hours = this.getHours(),
mins = this.getMinutes().pad(2);
ext = hours >= 12 ? "PM" : "AM";

return (hours % 12) + ":" + mins + ext;
};


Shouldn't the highlighted be a comma (',')?

Twey
12-22-2008, 06:38 AM
Should indeed. Thanks for that! *edits*

Nile
12-22-2008, 06:40 AM
Your welcome, and thanks for the tips. I just read your "common coding mistakes."