javascript倒计时呼应错误的时间

时间:2017-03-31 18:26:29

标签: javascript html countdown

我希望我的javascript代码能够在倒数3小时后阅读,并在倒计时完成后重定向到新页面

<script type="text/javascript">
// properties
var count = 0;
var counter = null;

window.onload = function() {
initCounter();
};

function initCounter() {
// get count from localStorage, or set to initial value of 1000
count = getLocalStorage('count') || 1000;
counter = setInterval(timer, 1000); //1000 will  run it every 1 second
}

function setLocalStorage(key, val) {
if (window.localStorage) {
  window.localStorage.setItem(key, val);
}

return val;
}

function getLocalStorage(key) {
return window.localStorage ? window.localStorage.getItem(key) : '';
}

function timer() {
count = setLocalStorage('count', count - 1);
if (count == -1) {
  clearInterval(counter);
  return;
}

var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;

document.getElementById("timer").innerHTML = hours +  "hours "  + minutes  +  "minutes and "   + seconds +  "  seconds left to complete this   transaction"; // watch for spelling
 }
</script>
<div id="timer"></div>

请让倒计时器完成倒计时三小时后再帮助我做得更好,并在倒计时结束后重定向到另一页

1 个答案:

答案 0 :(得分:2)

您没有正确设置总时间。您将其设置为16分钟而不是3小时。以下是工作代码(在JSFiddle上试用):

var time = 60 * 60 * 3;
var div = document.getElementById("timer");
var t = Date.now();

var loop = function(){
  var dt = (Date.now() - t) * 1e-3;

  if(dt > time){
    doWhateverHere();
  }else{
    dt = time - dt;
    div.innerHTML = `Hours: ${dt / 3600 | 0}, Minutes: ${dt / 60 % 60 | 0}, Seconds: ${dt % 60 | 0}`;
  }

  requestAnimationFrame(loop);
};

loop();

另外,请勿使用setIntervalsetTimeout进行精确计时。这些功能很不稳定。请改用Date.now()