使用LocalStorage保存数据

时间:2016-05-02 10:13:12

标签: javascript php timer local-storage

我正在尝试使用LocalStorage来保存数据。我想在用户刷新后使用此数据重新初始化计数器。我的代码示例可以在以下JSFiddle中找到。

var hj= document.getElementById("jam");
var mm= document.getElementById("menit");
var ds= document.getElementById("detik");


var startDateTime = new Date();
var startStamp = startDateTime.getTime();
console.log(startDateTime);
console.log(startStamp);
var newDate = new Date();
var newStamp = newDate.getTime();
// console.log(newStamp);
var timer;

function pad(val) {
    return val > 9 ? val : "0" + val;
}

function updateClock() {
    newDate = new Date();
    newStamp = newDate.getTime();
    var diff = Math.round((newStamp-startStamp)/1000);

    var d = Math.floor(diff/(24*60*60));
    diff = diff-(d*24*60*60);
    var h = Math.floor(diff/(60*60));
    diff = diff-(h*60*60);
    var m = Math.floor(diff/(60));
    diff = diff-(m*60);
    var s = diff;




    // document.getElementById("time-elapsed").innerHTML = d+" day(s), "+h+" hour(s), "+m+" minute(s), "+s+" second(s) working";
    document.getElementById("jam").innerHTML=pad(h);
    document.getElementById("menit").innerHTML=pad(m);
    document.getElementById("detik").innerHTML=pad(s);

}

var time=setInterval(updateClock, 1000);

https://jsfiddle.net/o5s4y2L7/

1 个答案:

答案 0 :(得分:1)

您可以使用Cookie。

var hj= document.getElementById("jam");
var mm= document.getElementById("menit");
var ds= document.getElementById("detik");


var startDateTime = new Date();
var cookie_time = getCookie("timer_start");
var startStamp = cookie_time?cookie_time:startDateTime.getTime();
setCookie("timer_start", startStamp, 1);
var newDate = new Date();
var newStamp = newDate.getTime();
var timer;

function pad(val) {
    return val > 9 ? val : "0" + val;
}

function updateClock() {
    newDate = new Date();
    newStamp = newDate.getTime();
      var diff = Math.round((newStamp-startStamp)/1000);

    var d = Math.floor(diff/(24*60*60));
    diff = diff-(d*24*60*60);
    var h = Math.floor(diff/(60*60));
    diff = diff-(h*60*60);
    var m = Math.floor(diff/(60));
    diff = diff-(m*60);
    var s = diff;




    document.getElementById("jam").innerHTML=pad(h);
    document.getElementById("menit").innerHTML=pad(m);
    document.getElementById("detik").innerHTML=pad(s);

}

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
} 

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length,c.length);
        }
    }
    return "";
} 
var time=setInterval(updateClock, 1000);