Silver time at Php Js
-
Hello! The problem was: long-term use lags time (in the first minute it is visible). Tell me how to fix it.
<?php
$timefin = '08:43:40'; date_default_timezone_set('Europe/Moscow'); ? ation
var hours = <? php echo date("H"); ?> ; var min = <? php echo date("i"); ?> ; var sec = <? php echo date("s"); ?> ; var finaltime = "<?php echo $timefin ?>";
function display() {
sec += 1;
if (sec >= 60) {
min += 1;
sec = 0;
}
if (min >= 60) {
hours += 1;
min = 0;
}
if (hours >= 24)
hours = 0;if (sec < 10)
sec2display = "0" + sec;
else
sec2display = sec;if (min < 10)
min2display = "0" + min;
else
min2display = min;if (hours < 10)
hour2display = "0" + hours;
else
hour2display = hours;time = hour2display + ":" + min2display + ":" + sec2display;
if (time == finaltime) {
$(document).ready(function() {$.ajax({ type: 'POST', url: 'response.php?', data: 'name=Andrew', success: function(data) { $('#show').html(data); } }); });
}
document.getElementById("seconds").innerHTML = hour2display + ":" + min2display + ":" + sec2display;
setTimeout("display();", 1000);
}
display();<b id="seconds">0</b>
<div id="show"></div>
-
Timers in JS are not exact.
setTimeout(..., 1000)
Not ideally equal to a second.It's a good option to give a time indicator function many times a second. Inside count the difference between the current time and the intended.
//var finaltime = "<?php echo $timefin ?>"; // timestamp var finaltime = Math.floor((new Date(2016,5,30,12,0,0)).getTime()/1000); var timerId = window.setInterval( display, 100); var el = document.getElementById("seconds");
function display() {
var seconds = Math.floor((finaltime - (new Date()).getTime()/1000))
,minutes
,hours
,days
;if (seconds <= 0) {
window.clearInterval( timerId);
$.ajax({
type: 'POST',
url: 'response.php?',
data: 'name=Andrew',
success: function(data) {
$('#show').html(data);
}
});
return;
}days = Math.floor(seconds/86400);
seconds = seconds % 86400;
hours = zeropad( Math.floor( seconds / 3600));
seconds = seconds % 3600;
minutes = zeropad( Math.floor( seconds / 60));
seconds = zeropad( seconds % 60);
el.innerHTML = days + ' д., ' + hours + ":" + minutes + ":" + seconds;
}function zeropad(n) {
return n < 10 ? '0'+n : n.toString();
}<b id="seconds">0</b>
<div id="show"></div>