我在网页上运行倒数计时器,但有时它运行不正常。它或多或少地运行20-30秒。当我移动到不同的标签时,它会再运行8-10秒。有没有办法准确运行计时器?
<script>
var display<?=$j ?> = document.querySelector('#time<?= $j ?>');
startTimer(<?= $differenceInSeconds?>, display<?=$j ?>,"<?= $res_tutor[$i]['student_id_fk'] ?>","row<?= $j ?>");
</script>
function startTimer(duration, display,student_id,row)
{
var start = Date.now(),
diff,
minutes,
seconds;
var stop;
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
hours = (diff / 3600) | 0;
minutes = (diff / 60)-(hours*60) | 0;
seconds = (diff % 60) | 0;
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent =hours + ":" + minutes + ":" + seconds;
if (diff <= 0) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
}
if((minutes == 0) && (seconds == 0))
{
// display.textContent ="Expired";
//jQuery("#"+row+" td:nth-child(2) a").css("pointer-events","none");
jQuery.ajax({
url: 'ajax_form_handler.php',
type: 'GET',
data: {'access':'true','action':'getUpdatedTime','student_id':student_id},
success: function(data) {
if(data>0)
{
console.log("duration is "+data);
duration=data;
}
else
{
if(data<=0)
{
duration=0;
}
display.textContent ="Timeout";
jQuery("#"+row+" td:nth-child(2) a").css("pointer-events","none");
console.log(">>>"+data);
clearTimeout(stop);
}
console.log(">>"+data);
},
error: function(e)
{
//alert("Some error occurred and request could not be completed.");
jQuery("#"+holder).html(ACTION_ERROR).fadeIn(100);
}
});
}
stop=setTimeout(timer, 1000);
}
// we don't want to wait a full second before the timer starts
timer();
//setInterval(timer, 1000);
}