所以在这里我创建了一个10分钟的倒数计时器,在按下“开始”按钮时启动。我想存储这个倒计时,以便当用户进入页面并返回时,倒计时仍将继续。请注意,我不希望倒计时停止,然后继续在页面重新加载时停止,我希望它继续指定截止日期。有什么建议吗?
<html>
<head>
</head>
<body>
<a id="sendButton" class="button" onclick=" startClock();">START</a>
<div id="sectionClock">
<div id="clockdiv">
<div>
<span class="hours"></span>
<div class="smalltext">Hours</div>
</div>
<div>
<span class="minutes"></span>
<div class="smalltext">Minutes</div>
</div>
<div>
<span class="seconds"></span>
<div class="smalltext">Seconds</div>
</div>
</div>
</div>
<script>
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
return {
'total': t,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
var flag = 0;
function startClock() {
/************ INITIALIZE CLOCK ************/
function initializeClock(id, endtime) {
// If countdown time is 0 then operate
if(flag==0)
{
var clock = document.getElementById(id);
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
flag=1;
}
function updateClock() {
var t = getTimeRemaining(endtime);
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
flag=0;
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
var timeInMinutes = 10;
var currentTime = Date.parse(new Date());
var deadline = new Date(currentTime + timeInMinutes*60*1000);
initializeClock('clockdiv', deadline);
document.cookie = deadline
var cookie = document.cookie;
console.log(cookie);
}
function sendTrack(){
(function() {
var trackUrl = document.getElementById("url");
}());
}
</script>
</body>
</html>
答案 0 :(得分:0)
你有正确的想法使用cookie,但you need to make sure you're reading/writing it correctly.我实际建议使用本地存储。
var deadline = localStorage.deadline;
if (deadline) { // Make sure we've saved one before
deadline = new Date(deadline);
} else { // Create a new one and save it
deadline = new Date(Date.now() + timeInMinutes*60*1000);
localStorage.deadline = deadline;
}