I’m working on a dashboard for a website, and one of the final features I’m adding is a clock. I have a basic function that gets the date/time, formats it, and outputs it into a clock, but my setInterval function isn’t working in Webkit browsers. I’ve tried re-arranging it a few different ways with no success.
In Webkit, the clock will reload if I force it to re-render by highlighting the clock text, or scrolling, etc.
My code looks like this:
$(document).ready(function() {
setInterval(function() {
var time = new Date();
var hour = time.getHours();
var min = time.getMinutes();
var sec = time.getSeconds();
var amPm = (hour < 12 ? "AM" : "PM");
hour = (hour <= 12 ? hour : hour - 12);
min = (min < 10 ? "0" + min : min);
sec = (sec < 10 ? "0" + sec : sec);
var currentTime = (hour + " : " + min + " : " + sec + " " + amPm);
$('#time').html(currentTime);
var date = time.getDate();
var month = time.getMonth();
var year = time.getYear();
year = year - 100;
var todaysDate = (month + "/" + date + "/" + year);
$('#date').html(todaysDate);
var dayNum = time.getDay();
var day = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
$('#day').html(day[dayNum]);
}, 1000);
});
It works in Firefox, but not in Chrome or Safari. Does anyone know why setInterval behaves strangely in Webkit, and what the fix is?
So as it turns out, there were a few bugs in my code. One being that the time object needs to be declared globally. Also, the best syntax is to wrap the whole thing into one function called
updateClock()and then use thesetIntervalon that, without()after the functionGood Luck