JS CountDown刷新时请不要重新加载

时间:2019-04-11 14:55:55

标签: javascript

好,我的代码应该可以工作,但是不能。每次重新加载时间时,我的Countdown都会从其初始值重新开始。

由于我对JS不熟悉,因此您也许可以使头脑平静

<script>
  var upgradeTime = 172801;
var seconds = upgradeTime;
function timer() {
  var days        = Math.floor(seconds/24/60/60);
  var hoursLeft   = Math.floor((seconds) - (days*86400));
  var hours       = Math.floor(hoursLeft/3600);
  var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
  var minutes     = Math.floor(minutesLeft/60);
  var remainingSeconds = seconds % 60;
  function pad(n) {
    return (n < 10 ? "0" + n : n);
  }
  document.getElementById('countdown').innerHTML = pad(days) + ":" + pad(hours) + ":" + pad(minutes) + ":" + pad(remainingSeconds);
  if (seconds == 0) {
    clearInterval(countdownTimer);
    document.getElementById('countdown').innerHTML = "Completed";
  } else {
    seconds--;
  }
}
var countdownTimer = setInterval('timer()',1000,function() {
            secondPassed();
            if (seconds === 0) {
                eraseCookie(seconds);
            } else {
                createCookie(seconds, seconds, 7);
            }
        });
</script>

我怎么称呼

<h1>Server Release in : <span id="countdown" class="timer"></span></h1>

我只希望我的计时器在每次重新加载页面时都不会刷新。 任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

你在这里。

var upgradeTime = 172801; //Timer length in ms
var timerMS = window.localStorage.getItem("date");
startTimer();

function timer() {
    var difference = timerMS - Date.now();
    if (difference <= 0) {
        startTimer();
        return;
    }
    var seconds = (difference / 1000).toFixed(0),
        days = Math.floor(seconds / 24 / 60 / 60),
        hoursLeft = Math.floor((seconds) - (days * 86400)),
        hours = Math.floor(hoursLeft / 3600),
        minutesLeft = Math.floor((hoursLeft) - (hours * 3600)),
        minutes = Math.floor(minutesLeft / 60),
        remainingSeconds = seconds % 60;

    function pad(n) {
        return (n < 10 ? "0" + n : n);
    }
    document.getElementById('countdown').innerHTML = pad(days) + ":" + pad(hours) + ":" + pad(minutes) + ":" + pad(remainingSeconds);
    setTimeout(timer, 1000);
}
function startTimer() {
    if (!timerMS || timerMS < Date.now()) {
        timerMS = Date.now() + upgradeTime;
        window.localStorage.setItem("date", timerMS);
    }
    timer();
}