javascript setInterval - countdown lagging [closed]

∥☆過路亽.° 提交于 2019-12-04 18:08:16

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.


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);

Working demo: http://jsfiddle.net/jfriend00/mxntj/

I've added this to the jfriend00 script to get 'minutes:secs' :

function minute(secs){
    minVar = Math.floor(secs/60);
    secs = secs % 60;
    if (secs < 10) {
        secs = "0"+secs;
    }
    return minVar+":"+secs;
}

Added to : elem.innerHTML = minute(Math.round(cnt / 1000)); and document.getElementById("countdown").innerHTML = minute(secs);

Thanks to you all.

I needed to do add 'clearInterval(ticker);' at the beginning of function startTimer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!