将localStorage添加到Javascript倒计时器

时间:2015-07-04 05:45:22

标签: javascript timer

我需要一个倒数计时器,所以我将这个Javascript编码添加到我的网站页面。唯一的问题是,当用户点击浏览器中的重新加载按钮时,计时器每次都会重置。有人告诉我,我需要添加 localStorage 来阻止这种情况发生。我需要添加哪些代码来修复此问题?

function startTimer(duration, display) {
  var start = Date.now(),
    diff,
    minutes,
    seconds;

  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
    minutes = (diff / 60) | 0;
    seconds = (diff % 60) | 0;
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    display.textContent = 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;
    }
  };
  // we don't want to wait a full second before the timer starts
  timer();
  setInterval(timer, 1000);
}
window.onload = function() {
  var thirtyMinutes = 60 * 30,
    display = document.querySelector('#time');
  startTimer(thirtyMinutes, display);
};

0 个答案:

没有答案