Search code examples
phpdatereloadmillisecondshour

jQuery/PHP: Refresh page according to server time


I'm trying to make a jQuery script for reloading the complete page. This is the code I got so far;

<script type="text/javascript">
setInterval("refresh();",5000);
function refresh(){
    window.location = location.href;
}
</script>

This works perfectly for reloading the complete page every 5 seconds, but I'm trying to push this a bit further. What I want to accomplish is that the page reloads every new hour according to the server time. Let's say that the time is now 10:50PM. I want the script to update the page at 11:00PM when it's a new hour. (10 minutes after the user has visited the page). If the time is 10:55PM when the user enters, the script needs to refresh the page 5 minues after the user entered the page and so on.

Is there any easy way to do this? I can use the date() function in PHP to calculate the time remaining in the current hour. I have this script so far;

<?php
$date = date("i:s");

list($cur_min, $cur_sec) = explode(':', $date);

$mins_left = ($cur_min == 59) ? 0 : 60 - $cur_min;
$secs_left = 60 - $cur_sec;

echo 'There is ' . ($mins_left)  . ' minutes and ' . $secs_left . ' seconds left until the next hour';
?>

This works perfectly to display the time left until the next hour. So far so good. What I'm now struggling with is to get the time left until the next hour in milliseconds. This way I can use PHP to create a string with the milliseconds left and use that in the jQuery script. For example save the total milliseconds left in the hour in $timeleft. If I can achieve that, the jQuery script would be very simple. Like this;

<script type="text/javascript">
setInterval("refresh();",<?php echo $timeleft ?>);
function refresh(){
    window.location = location.href;
}
</script>

Any help would be highly appreciated!


Solution

  • <?php
    $date = date("i:s");
    
    list($cur_min, $cur_sec) = explode(':', $date);
    
    $mins_left = ($cur_min == 59) ? 0 : 60 - $cur_min;
    $secs_left = 60 - $cur_sec;
    
    echo 'There is ' . ($mins_left)  . ' minutes and ' . $secs_left . ' seconds left until the next hour';
    $time=($mins_left*60+$secs_left)*1000;
    ?>
    <script type="text/javascript">
    setInterval("refresh()",<?php echo $time; ?>);
    function refresh(){
    window.location = location.href;
    }
    </script>
    

    Please try this hope it is helpful