大家好,我有一个项目,而我在制作项目时遇到了问题。我已经为考试计时器编写了代码,并且成功倒计时。我遇到的问题是当刷新网页时,计时器返回到初始计算。请帮我解决问题。我正在使用laravel框架。
var upgradeTime= {{$d->time*60}};
var seconds = upgradeTime;
function timer() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('time').innerHTML = pad(hours) + ":" + pad(minutes) + ":" + pad(remainingSeconds);
if (seconds == 0) {
clearInterval(countdownTimer);
alert('Waktu habis.');
document.getElementById("regForm").submit();
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
[如果您希望倒数计时器在刷新页面时继续运行,则应将“剩余时间”存储在以下位置:您可以通过javascript将其存储在cookie中,也可以发送ajax请求并将其存储在服务器中。
对于js解决方案,您可以执行以下操作:(关于setCookie和getCookie函数,请参见this question。
var upgradeTime= {{$d->time*60}};
var seconds;
var countdownTimer;
function timer() {
/// YOUR TIMER CODE HERE
/// JUST store the remaining time in cookie at the end:
setCookie('remainingTime', seconds, 1);
}
$(document).ready(function () {
var remainingTime = 0;
if (getCookie('remainingTime')) {
//get from cookie if it was previously stored
remainingTime = getCookie('remainingTime');
console.log(getCookie('remainingTime'));
} else {
//use the default value
remainingTime = upgradeTime;
setCookie('remainingTime', remainingTime, 1);
}
if (remainingTime > 1) {
seconds = remainingTime;
countdownTimer = setInterval(timer, remainingTime);
}
});