phphtmlrefreshclocklive-update

Alternative To Page Refresh PHP


I'm working on learning PHP and I wanted to make a clock with some crypto-like number images I made.

The problem I'm running in to is that I want the clock to be updated every second but without refreshing the page. So my question is, how would you suggest I go about doing this?

Right now I use the HTML page refresh which causes my images to flicker every reload.

Thank you in advance for your help!

Code below:

<!--
    * By megabyteGhost
    * megabyteGhost.tumblr.com
-->


<html>
    <head>
        <meta http-equiv="refresh" content="0.5" >
    </head>

    <body bgcolor="black">
    <?php
        date_default_timezone_set('America/New_York');
        $hour = date(H); 
        $minutes = date(i);
        $seconds = date(s);

        echo '<img src="images/'.$hour.'.png">';
        echo '<img src="images/'.$minutes.'.png">';
        echo '<img src="images/'.$seconds.'.png">';
    ?>

    </body>
</html>

Solution

  • You can (only) use Javascript:

    (i added alt tag, because the images obiously can't be loaded here)

    setInterval(function(){
      var date = new Date();
      
      var hr = date.getHours();
      var min = date.getMinutes();
      var sec = date.getSeconds();
      
      //document.getElementById("hours").src = "images/" + hr + ".png";
      document.getElementById("hours").alt = hr;
      //document.getElementById("minutes").src = "images/" + min + ".png";
      document.getElementById("minutes").alt = min;
      //document.getElementById("seconds").src = "images/" + sec + ".png";
      document.getElementById("seconds").alt = sec;
    },1000)
    <span id="timer">
      <img src="" id="hours" alt="0">:
      <img src="" id="minutes" alt="0">:
      <img src="" id="seconds" alt="0">
    </span>

    be aware that you should preload the images!

    JS:

    //before starting the interval:
    var preloadedImages = [];
    for(var i=0;i<60;i++){
        preloadedImages[i] = new Image();
        preloadedImages[i].src = "images/"+i+".png";
    }
    

    whis way, the browser keeps them in memory, so you won't have a flickering second counter when the images are loaded for the first time

    [EDIT]: By the way....avoid this:

    $hour = date(H); 
    $minutes = date(i);
    $seconds = date(s);
    

    should be this:

    $hour = date("H"); 
    $minutes = date("i");
    $seconds = date("s");
    

    else they will be checked as constant variables and print out a notice, which will spam your logs, if you have the log level low enough...also, it needs more processing time (no big deal with only three calls, but is accumulative if used more often...)