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?
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();
});
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:
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..time, change it. This assumes that result is a string like 11:08:00function 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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With