【问题标题】:continue count down after refresh刷新后继续倒计时
【发布时间】:2021-02-15 19:50:38
【问题描述】:

计数器正常工作,但刷新后重新启动 刷新计数器后如何继续?

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);
  
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
  
        display.textContent = minutes + ":" + seconds;
  
        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
  }
  
  window.onload = function () {
    var duration = 60 * 2,
        display = document.getElementById("timer");
    startTimer(duration, display);
  };

【问题讨论】:

  • 将计数存储在localStorage 中,并在页面加载时检查其中是否有计数,如果有,请将计数初始化为该计数。
  • @ScottMarcus - 对这个说法很好奇:“刷新计数器后如何继续?” - 不知道 OP 是否意味着页面。给定上面的代码,时间在到达零时重新开始。
  • 您的意思是您不想让计时器重新开始倒计时吗?如果是这种情况,1. 将setInterval 的输出分配给一个变量; 2. 在if 语句中将timer = duration; 更改为clearInterval(variableNameSetBySetInterval)

标签: javascript counter countdown countdowntimer


【解决方案1】:

您可以尝试使用 localStorage。 localStorage 与 sessionStorage 类似,只是 localStorage 中存储的数据没有过期时间,而 sessionStorage 中存储的数据会在页面会话结束时被清除。 例如:

localStorage.setItem("duration",60);
localStorage.getItem("duration"); //60

查看此文档: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

【讨论】:

    猜你喜欢
    • 2019-06-01
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多