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
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>
<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"> </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.
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 (',')?
Should indeed. Thanks for that! *edits*
Your welcome, and thanks for the tips. I just read your "common coding mistakes."
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.