Jul 23 2009 Programming

Here's a UTC clock   and a countdown timer   I wrote for a friends game.


Yes it's a simple little thing. But when you consider the code it replaced. Which was an AJAX request with a timeout of 500 milliseconds. The servers performance improved considerably to say the least.

<script>
// i is originally set with PHP's date() function. A nice unix timestamp then multiplied by 1000 to convert to milliseconds.
var i = new Date; i = i.getTime(i);

function set_date() {
    var a = new Date(i);
    var b = a.getUTCHours(); b = b.toString(); // for length
    if ( b.length < 2 ) { b = "0" + b } // zero pad single digits
    var c = a.getUTCMinutes(); c = c.toString();
    if ( c.length < 2 ) { c = "0" + c }
    var d = a.getUTCSeconds(); d = d.toString();
    if ( d.length < 2 ) { d = "0" + d }
    var string = b+":"+c+":"+d;
    document.getElementById("clock").innerHTML = string;
    i += 1000;
}

setInterval( "set_date()", 1000 );
</script>

<div id="clock">&nbsp;</div>

<script>

    // The logout time was set in a cookie and we parsed the time from them here.

    //var allcookies = document.cookie;
    //var pos = allcookies.indexOf("cookieexpire=");
    //var start = pos + 13;
    //var end = allcookies.indexOf(";", start);
    //if (end == -1) end = allcookies.length;
    //var value = allcookies.substring(start, end);

    // var a = value * 1000;
    var a = 1237213552;


    //var b = new Date(i);
    //var c = Math.floor(b.getTime() / 1000);

    // Again unix time via PHP.
    var i = 1237211552;
    var timeleft = a - i;

function log_out() {
    if ( timeleft <= 0 ) { document.getElementById("logout").innerHTML = "00:00:00"; return }
    var h, m, s, tmp;
    if ( timeleft > 3600 ) { h = "01"; tmp = Math.floor(timeleft - 3600) }
    else { h = "00"; tmp = timeleft }

    m = Math.floor(tmp / 60 ); m = m.toString(); if ( m.length < 2 ) { m = "0" + m }
    s = Math.floor(tmp % 60 ); s = s.toString(); if ( s.length < 2 ) { s = "0" + s }
    document.getElementById("logout").innerHTML = h+":"+m+":"+s;
    timeleft--;
}

setInterval("log_out()", 1000);
</script>

<div id ="logout">&nbsp;</div>


Download

   
Comments
No comments.
Comments for this entry available via RSS.
Comment Area
Your Name
Your Email (will not be published)
Your Website
Your Comment
Profanity is Prohibited
eric.dziewa.com is running WordPress.
WhiteSpace theme designed by E. Dziewa.
All content © E. Dziewa.
Thanks for stopping by.