Javascript计时器不准确
我正在运行网页中的倒计时,但它有时运行不正常。它运行20-30秒左右。当我移动到不同的选项卡时,它会多运行8-10秒。有没有办法精确地运行计时器Javascript计时器不准确,javascript,jquery,timer,countdown,Javascript,Jquery,Timer,Countdown,我正在运行网页中的倒计时,但它有时运行不正常。它运行20-30秒左右。当我移动到不同的选项卡时,它会多运行8-10秒。有没有办法精确地运行计时器 <script> var display<?=$j ?> = document.querySelector('#time<?= $j ?>'); startTimer(<?= $differenceInSeconds?>, display<?=$j ?>,"<?= $r
<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);
}
var display=document.querySelector(“#time”);
startTimer(,display,“,”行“);
功能启动计时器(持续时间、显示、学生id、行)
{
var start=Date.now(),
差异,
会议记录,
秒;
var停止;
函数计时器(){
//获取此后经过的秒数
//调用了startTimer()
diff=持续时间-((Date.now()-start)/1000)| 0);
//执行与parseInt相同的任务来截断浮点值
小时数=(差值/3600)| 0;
分钟=(差异/60)-(小时*60)| 0;
秒=(差异%60)| 0;
小时=小时<10?“0”+小时:小时;
分钟=分钟<10?“0”+分钟:分钟;
秒=秒<10?“0”+秒:秒;
display.textContent=小时+“:”+分钟+“:”+秒;
如果(差异0)
{
console.log(“持续时间为”+数据);
持续时间=数据;
}
其他的
{
如果(数据)