目前,我的代码中有这个JavaScript
function startTimer(duration, display) {
var timer = duration,
minutes, seconds;
setInterval(function() {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = 0;
}
}, 1000);
}
window.onload = function() {
var fiveMinutes = 60 * 0.18,
display = document.querySelector('#time');
startTimer(fiveMinutes, display); //`enter code here`
};
<div id="time"></div>
刷新时如何让计时器继续运行?是否只使用cookie?
答案 0 :(得分:0)
如果您在服务器端没有像数据库这样的内容和/或用户没有登录,我认为cookie是您最好的选择:
这可能有助于您开始,定义set并获取每个
的cookie函数SET
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;
}
GET
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 "";
}
在您的文档中的某个位置,也许在您的计时器中,将Cookie设置为:
setCookie("minutes", minutes.toString(), 1);
setCookie("seconds", seconds.toString(), 1);
然后在你的on load事件的某个地方通过get函数设置变量,如:
minutes = getCookie("minutes");
seconds = getCookie("seconds");
答案 1 :(得分:0)
这只是关于如何制作cookie的指针,这里是工作代码。看看这里的小提琴:https://jsfiddle.net/edencorbin/hht4yqka/1/你需要调整计时器,我把它设置为10:00。
<script>
var minutes = 0;
var seconds = 0;
function startTimer(duration, display) {
var timer = duration,
minutes, seconds;
setInterval(function() {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
setCookie("minutes", minutes.toString(), 1);
setCookie("seconds", seconds.toString(), 1);
if (--timer < 0) {
timer = 0;
}
}, 1000);
}
window.onload = function() {
var minutes_data = getCookie("minutes");
var seconds_data = getCookie("seconds");
var timer_amount = (60*10); //default
if (!minutes_data || !seconds_data){
//no cookie found use default
}
else{
timer_amount = parseInt(minutes_data*60)+parseInt(seconds_data)
}
var fiveMinutes = timer_amount,
display = document.querySelector('#time');
startTimer(fiveMinutes, display); //`enter code here`
};
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 "";
}
</script>
<div id="time"></div>