Я пытаюсь использовать 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);
Вы можете использовать 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);
Других решений пока нет …