刷新后倒计时重启的解决方案

时间:2017-03-28 11:11:04

标签: jquery countdowntimer

请帮助我使用我的倒计时代码重新启动我刷新页面的所有内容。此外,分钟和秒数同时计算在一起

以下是我目前的javascript代码;

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 * 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 fiveMinutes = 60 * 2,
        display = document.querySelector('#time');
    startTimer(fiveMinutes, display);
};
<div id="time"></div>

请帮助我........提前致谢

2 个答案:

答案 0 :(得分:1)

你走了。这有点乱,但我很匆忙,所以你必须自己整理一下;)

我使用本地存储来存储时间,当你刷新它时会检查本地存储并加载相应的时间。

HTML:

<div id="time"></div>

JS:

function countDown(minutes, seconds) {
  var currentTime;

  function twoDigits(n) {
    return (n <= 9 ? '0' + n : n);
  }

  function updateTimer() {
    msLeft = endTime - (+new Date);
    time = new Date(msLeft);
    hours = time.getUTCHours();
    mins = time.getUTCMinutes();
    currentTime = (hours ? hours + ':' + twoDigits(mins) : mins) + ':' + twoDigits(time.getUTCSeconds());
    localStorage.setItem('timer', currentTime);
    $('#time').text(currentTime);
    countDownTimer = setTimeout(updateTimer, time.getUTCMilliseconds() + 500);
  }

  endTime = (+new Date) + 1000 * (60 * minutes + seconds) + 500;
  updateTimer();
}

if (localStorage.getItem('timer')) {
  localTime = localStorage.getItem('timer');
  var minutes = parseInt(localTime.substr(0, localTime.indexOf(':')));
  var seconds = parseInt(localTime = localTime.split(':')[1]);

  countDown(minutes, seconds);
} else {
  countDown(120, 0);
}

Fiddle

答案 1 :(得分:0)

您可以使用localStorage或Cookie。 Cookie最适合与服务器端通信一起使用,如果用户尝试在倒计时中作弊,则可以监视用户活动。 LocalStorage位于客户端,因此客户可以随意操作。但是,两种方式都有可能,请看下面的样本,这是安静的,很抱歉。希望这对你有所帮助。顺便说一句,cookie不会在localhost上运行,你的页面应该在node.js或类似的环境中运行。

HTML:

<div id="time"></div>

JS

var _time = 0;
var _cookie_val = {hours:"", minutes:"", seconds:""};

//change seconds to HH:MM:SS
//http://stackoverflow.com/questions/6312993/javascript-seconds-to-time-string-with-format-hhmmss
String.prototype.toHHMMSS = function () {
    var sec_num = parseInt(this, 10);
    var hours   = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    var seconds = sec_num - (hours * 3600) - (minutes * 60);
    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    return {hours:hours, minutes:minutes, seconds:seconds};
}


//get Cookie
let _getCookie = function(args) {
  var _cookie_Val = "; " + document.cookie;
  var _splits = _cookie_Val.split("; " + args + "=");
  if (_splits.length==2) return _splits.pop().split(";").shift();
}

//set cookie
let _cookie = function (args) {
  document.cookie = "_hours=" + args.args_toHHMMSS.hours;
  document.cookie = "_minutes=" + args.args_toHHMMSS.minutes;
  document.cookie = "_seconds=" + args.args_toHHMMSS.seconds;
  document.cookie = "args=" + args.args;
};


var _timer = function (args) {
  //set _time to args if _getCookie('args') is undefined or empty
  var _time = _getCookie("args") || args;

  //convert val to string and set cookie
  _cookie({args_toHHMMSS: _time.toString().toHHMMSS(), args: _time});

  //get cookie    _getCookie(_hours || _minutes || _seconds || args)
  // console.log(_getCookie("args").toString().toHHMMSS());
  var update_print = _getCookie("_hours") + ":" +
                     _getCookie("_minutes") + ":" +
                     _getCookie("_seconds");
  document.querySelector('#time').textContent = update_print;


  //start interval
  let _interval = setInterval( function(){

    //convert val to string and set cookie
    _cookie({args_toHHMMSS: _time.toString().toHHMMSS(), args: _time});

    //get cookie    _getCookie(_hours || _minutes || _seconds || args)
    var update_print = _getCookie("_hours") + ":" +
                       _getCookie("_minutes") + ":" +
                       _getCookie("_seconds");
    document.querySelector('#time').textContent = update_print;


    //stop interval when time reaches 0
    if(_time <= 0){
      //finite loop
      clearInterval(_interval);

      //infinite loop
      //_time = args;

    }else{ _time--; }
  },1000);
}



//onload this function will be executed
window.onload = () => {
  var seconds = 5; //enter the desired minute. e.g 300 for 5 min
  _timer(seconds); //call _timer with argument seconds
};