Forum Moderators: open

Message Too Old, No Replies

JS/PhP clock script cross browser issues

         

Readie

6:19 am on Feb 22, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Ok, I wrote a clock script in JavaScript on one of my websites, using the PhP date() function to fill the base values. It works fine in Internet Explorer, however in Chrome and Opera (Not checked it in any others) it's failing to loop.

The code (with 0 default values set, rather than PhP) is as follows:

var hh = 0;
var mm = 0;
var ss = 0;
var phh = "00";
var pmm = "00";
var pss = "00";

window.onload=function timer(){
ss += 1;
if(ss != 60) {
if(ss <= 9) {
pss = "0" + ss;
} else {
pss = ss;
}
} else {
ss = 0;
pss = "00"
mm += 1;
if(mm <= 9) {
pmm = "0" + mm;
} else {
pmm = mm;
}
}

if(mm == 60) {
mm = 0;
pmm = "00";
hh += 1;
if(hh <= 9) {
phh = "0" + hh;
} else {
phh = hh;
}
}

if(hh == 24) {
hh = 0;
phh = "00";
}

document.getElementById('chh').innerHTML = phh;
document.getElementById('cmm').innerHTML = pmm;
document.getElementById('css').innerHTML = pss;
window.setTimeout('timer()',1000);
}

-----
<span id="chh">00</span>:<span id="cmm">00</span>:<span id="css">00</span>


I've tried creating another function, and rephrasing the end of the script like this:

window.setTimeout('loop()',500);
}

function loop(){
window.setTimeout('timer()',500);
}


Wondering if what Chrome and Opera dislike is a self-calling function, but to no avail.

Since the seconds increase by one on Chrome and Opera, I can surmise that the issue here is setTimeout - I was wondering if anyone knows of a working alternative to infinite loops for non-IE users?

daveVk

8:37 am on Feb 22, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



May be scope issue

replace
window.onload=function timer(){
with
function timer(){ // make sure timer defined with global scope

then later set
window.onload=timer;

Readie

4:11 pm on Feb 22, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yup, that fixed it - thanks :)