希望javascript倒计时从刷新后的地方继续

时间:2017-03-31 07:22:23

标签: javascript html

我正在使用以下代码设计一个javaScript倒计时3小时

<div id="timer"></div>
<script type="text/javascript">
var count = 10800;
var counter = setInterval(timer, 1000); //1000 will  run it every 1 second

function timer() {
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>

但我在这里遇到的唯一问题是每当我刷新页面时倒计时再次开始。我希望它从它停止的地方恢复。

1 个答案:

答案 0 :(得分:1)

您需要将数据存储到某些持久性存储方法中,例如cookie,浏览器localStorage,或将数据写入外部数据源(例如通过API的数据库)。否则,浏览器刷新之间的会话数据将丢失。

例如,如果您想使用localStorage:

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

您可以在此处试用:https://jsfiddle.net/rcg4mt9x/