I have been trying to figure out how to refresh the time (and only the time) automatically in my webpage, but I can't seem to get it.
This is what I have.
var d = new Date();
var weekday = d.getDay();
var day = d.getDate();
var month = d.getMonth() + 1; //JS says jan = 0
var year = d.getFullYear();
var minutes = d.getMinutes();
var hours = d.getHours() + 1; //eastern time zone
var seconds = d.getSeconds();
var ms = d.getMilliseconds();
function distime(minutes, hours, month, day, year) {
if (minutes < 10) {
var lowMin = "0" + minutes.toString();
document.getElementById("timecode").innerHTML = hours.toString() + ':' + lowMin + ' ' + month.toString() + '/' + day.toString() + '/' + year.toString();
alert("here");
} else
document.getElementById("timecode").innerHTML = hours.toString() + ':' + minutes + ' ' + month.toString() + '/' + day.toString() + '/' + year.toString();
alert("here");
};
// var clockTime = distime(minutes, hours, month, day, year);
function init(minutes, hours, month, day, year) {
alert("init");
distime(minutes, hours, month, day, year);
setTimeout(distime, 10000);
};
var initTime = init(minutes, hours, month, day, year);
The time is attached to a div, in HTML and I am not using PHP.
I have heard that I need to use ajax to do this, but I'm not sure how to implement that.
Again, my question is: How do I refresh the time every 10 seconds so that it will display correctly on my site.
Thanks!
The updated code that solved my problem can be seen below.
var time = {};
(function () {
var clock = document.getElementById('timecode');
(function tick () {
var minutes, d = new Date();
time.weekday = d.getDay();
time.day = d.getDate();
time.month = d.getMonth() + 1; //JS says jan = 0
time.year = d.getFullYear();
time.minutes = d.getMinutes();
time.hours = d.getHours() + 1; //eastern time zone
time.seconds = d.getSeconds();
time.ms = d.getMilliseconds();
minutes = (time.minutes < 10 ? '0' + time.minutes : time.minutes);
clock.innerHTML = time.hours + ':' + minutes + ' ' + time.month + '/' + time.day + '/' + time.year;
window.setTimeout(tick, 1000);
}()); // Note the parens here, we invoke these functions right away
}()); // This one keeps clock away from the global scope
Thanks to everyone who helped!