防止计时器重置

时间:2014-07-18 07:58:02

标签: javascript jscript

我正在制作一个倒数计时器脚本,当时间到达0时退出程序。

问题是当页面重新加载时,计时器从头开始再次启动..

有没有办法阻止计时器重置?

  // set the date we're counting down to
  var target_date = new Date().getTime();
  var delay=100;
  // variables for time units
  var days, hours, minutes, seconds;

  // get tag element
  var countdown = document.getElementById("countdown");

  // update the tag with id "countdown" every 1 second
  setInterval(function () {

        // find the amount of "seconds" between now and target
        var current_date = new Date().getTime();
        var seconds_left = (current_date - target_date) / 1000;
        var a=(delay-seconds_left);
        // do some time calculations

        minutes = parseInt(a / 60);
        seconds = parseInt(a % 60);
        var progress = a/delay*100;

        // format countdown string + set tag value
        countdown.innerHTML = '<div  Class=outer style="font-size:20px;width:'+progress+'%">'+minutes + "m: " + seconds + "s" + '</div>';

        if(a <= 0)
        {
        window.open("a.html")

        self.close();
        //var wind = window.open("a.html");    
        }

  }, 1000);

2 个答案:

答案 0 :(得分:1)

您可以将target_date存储在本地存储(或Cookie)中,并在页面加载时查找它。 E.g:

var target_date = localStorage.target_date;
if (target_date) {
    // Found it in local storage, turn the string into a number
    target_date = parseInt(target_date);
} else {
    // Didn't find it in local storage, get the target and 
    target_date = new Date().getTime(); // See below, this looks weird
    localStorage.target_date = String(target_date);
}

本地存储空间为quite well-supported in modern browsers

请注意,只有字符串和某些其他存储兼容的项目可以存储在本地存储中,这就是我明确处理上述数字的字符串版本的原因。如果您需要存储更复杂的信息,JSON通常是一种有用的格式。


初始化target_date的代码对我来说没有多大意义:它抓住时间现在。我希望倒计时能够为target_date抓住未来的时间。在任何情况下,根据需要更换该行(或替换您正在存储的内容)。

答案 1 :(得分:1)

或者,您始终可以将当前时间放入cookie中,并在加载页面时加载该cookie。 Learn more about Cookies here.

相关问题