javascript setInterval - 倒计时滞后 [英] javascript setInterval - countdown lagging

查看:199
本文介绍了javascript setInterval - 倒计时滞后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的代码在几秒钟内倒计时。问题是,当使用jquery .load再次加载包含倒计时的页面部分时,新的倒计时会出错:每隔一秒,我们会看到快速的2秒,如下所示:9-8 ... 7-6。 ..5-4 ......仿佛它与时钟不同步......在那里看到:aorbaroquethrash.com/test(为了解决问题,我必须在你去的时候改变歌曲)

I use this code below for a countdown in seconds. The problem is that when the part of the page including the countdown is loaded again using jquery .load, the new countdown becomes wrong : at every second, we see fast 2 seconds, like this : 9-8...7-6...5-4... as if it was not synchronised with the clock... See it there : aorbaroquethrash.com/test (for the problem to happen, I have to change song while you're there)

我知道如何解决这个问题?

Any idea how I can solve this?

<script type = "text/javascript">
/*author Philip M. 2010*/

var timeInSecs;
var ticker;

function startTimer(secs){
timeInSecs = parseInt(secs)-1;
ticker = setInterval("tick()",1000);   // every second
}

function tick() {
var secs = timeInSecs;
if (secs>0) {
timeInSecs--;
}
else {
clearInterval(ticker); // stop counting at zero
}

document.getElementById("countdown").innerHTML = secs;
} 
startTimer(<?php echo $stream['info']['length'];?>);

</script>

Patrick

推荐答案

您应该使用当前系统时间来显示或计算经过的秒数,而不是自己计算。 setInterval()不能保证按时完美调用,当你自己计算时可能会累积错误,如果没有调用你会显示错误的时间时间。

You should be using the current system time to display or calculate how many seconds have elapsed rather than doing your own count. setInterval() is not guaranteed to be called perfectly on time and you can potentially get accumulating error when you just count yourself and you will display the wrong time if it isn't called on time.

记录您开始计算的时间,然后记录每次打勾,获取新的系统时间并计算自开始计数以来没有累积错误的时间。

Record the time that you start countingand then on each tick, get the new system time and calculate how much time has elapsed since you started counting with no accumulating error.

另外,请不要将字符串传递给 setInterval()。传递一个真正的函数引用,因为这可以防止作用域问题和其他潜在的问题。

Also, please don't pass strings to setInterval(). Pass a real function reference as this prevents scoping issues and other potential problems.

以下是倒计时工作代码的示例计时器:

Here's an example of working code for a countdown timer:

var startTime, countAmt, interval;

function now() {
  return ((new Date()).getTime());
}

function tick() {
  var elapsed = now() - startTime;
  var cnt = countAmt - elapsed;
  var elem = document.getElementById("counter");
  if (cnt > 0) {
    elem.innerHTML = Math.round(cnt / 1000);
  } else {
    elem.innerHTML = "0";
    clearInterval(interval);
  }
}

function startTimer(secs) {
  clearInterval(interval);
  document.getElementById("counter").innerHTML = secs;
  countAmt = secs * 1000;
  startTime = now();
  interval = setInterval(tick, 1000);  
}

startTimer(20);

工作演示: http://jsfiddle.net/jfriend00/mxntj/

这篇关于javascript setInterval - 倒计时滞后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆