0

我做了一个计时器。主题是让它从最后一个页面访问后停止的点开始。例如,它是“00:02:21”,重新加载页面后,它从这一点开始,而不是从一开始。为此,我决定使用 cookie。

这个想法是从cookie中获取时间变量并使用它,然后在cookie中重写时间

示例(http://jsfiddle.net/JuxZr/):

function simple_timer(sec, block) {
document.cookie = 'window.time=sec; expires=Thu, 2 Aug 2091 20:47:11 UTC; path=/; ;domain=.nekamera.ru'

var day = Math.floor(time / 86400);
time = (time - day * 86400);

var hour = Math.floor(time / 3600);

time = (time - hour * 3600);

if ( hour < 10 ) hour = '0'+hour;
var minutes = Math.floor(time / 60);
time = (time - minutes * 60);
if ( minutes < 10 ) minutes = '0'+minutes;
var seconds = time;
if ( seconds < 10 ) seconds = '0'+seconds;
block.innerHTML =  day + ' days ' +  hour+':'+minutes+':'+seconds;
sec--;
    if ( sec > 0 ) {
        setTimeout(function(){ simple_timer(sec, block); }, 1000);
    } else {
         simple_timer(15, block);}
       }

function start_countdown() {
    var block = document.getElementById('sample_countdown'); //restart the timer live
    simple_timer(15, block);
}


window.onload=start_countdown;
4

1 回答 1

0

window.time=sec在行中:

document.cookie = 'window.time=sec; expires=Thu, 2 Aug 2091 20:47:11 UTC; path=/; ;domain=.nekamera.ru'

解析器从未真正解释过,而仅存储为字符串。您要做的是以字符串格式存储时间,然后将该字符串解析为后续请求中的变量。

设置cookie:

document.cookie = 'time=' + sec + '; expires=Thu, 2 Aug 2091 20:47:11 UTC; path=/; ;domain=.nekamera.ru'

读取 cookie:

// from w3schools
function getCookie(c_name)
{
    var c_value = document.cookie;
    var c_start = c_value.indexOf(" " + c_name + "=");
    if (c_start == -1) {
        c_start = c_value.indexOf(c_name + "=");
    }
    if (c_start == -1) {
        c_value = null;
    } else {
        c_start = c_value.indexOf("=", c_start) + 1;
        var c_end = c_value.indexOf(";", c_start);
        if (c_end == -1) {
            c_end = c_value.length;
        }
        c_value = unescape(c_value.substring(c_start,c_end));
    }
    return c_value;
}

var time = parseInt(getCookie('time'));
于 2013-09-03T13:43:29.597 回答