Hello! Faced a problem: with prolonged use, time is lagging behind (within the first minute it is already noticeable). Tell me how to fix it.

<?php 

$ timefin = '08: 43: 40 '; date_default_timezone_set ('Europe / Moscow'); ?>

 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> 

    1 answer 1

    Timers in JS are not accurate. setTimeout(..., 1000) not ideally equal to second.

    A good option is to call the time display function many times per second. Inside, consider the difference between the current time and the specified one.

     //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> 

    • Thank you, this is what I need! But how to do what would take time from the server and not the computer? - Bogdan