Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX jQuery - update content every full minute

I'm thinking on a clock that will refresh every full minute if system clock on users computer will look like this eg. 11:08:00, it'll refresh and 11:09:00 etc.

I've tryed to setInterval():

setInterval(function(){
    $.ajax({
        url: "../time.php",
        context: document.body,
        success: function(result){
            $('.time').html(result);
        }
    })
}, 60000);

But it's reloading every minute after page load.

Is there any solution?

like image 513
arclite Avatar asked Jan 23 '26 22:01

arclite


2 Answers

Try this code:

var interval    =   0;
function start(){
    setTimeout( function(){
        ajax_function();
        interval    =   60;
        setInterval( function(){
            ajax_function();
        }, interval * 1000);
    }, interval * 1000);    
}

function ajax_function(){
    $.ajax({
        url: "../time.php",
        context: document.body,
        success: function(result){
            $('.time').html(result);
        }
    }); 
}

$( window ).load(function(){
    var time    =   new Date();
    interval    =   60 - time.getSeconds();
    if(interval==60)
        interval    =   0;
    start();
});
like image 142
Sherin Jose Avatar answered Jan 25 '26 12:01

Sherin Jose


setInterval() won't invoke its function immediately, the first time the function runs in this case will be 60 seconds after page load. You can make the following changes to get the result you're looking for:

  • Place your AJAX request in a function
  • Call the function as soon as the page loads
  • Use setTimeout() in the success function of .ajax(), rather than setInterval() around the whole thing. If there is an error with the request, setInterval() will carry on regardless, but setTimeout() won't go again until the request is successful.
  • Split the result, taking the seconds away, and if the result is different to what is already in .time, change it. This assumes that result is a string like 11:08:00
  • If you want to acknowledge when the server returns a time where the minute has changed, you need to check it every second
function update(){
    $.ajax({
        url: "../time.php",
        context: document.body,
        success: function(result){
            var secondless = result.split(':'), $time = $('.time');
            secondless = secondless [0]+':'+secondless [1];
            $time.html(function(_,v){
                return secondless != v ? secondless : v
            }
            setTimeout(update, 1000);
        }
    })
}
update();
like image 23
George Avatar answered Jan 25 '26 13:01

George