gpt4 book ai didi

javascript - 将 cookie 实现到简单的秒表中

转载 作者:行者123 更新时间:2023-12-03 10:52:12 25 4
gpt4 key购买 nike

我有简单的stopwatch在javascript中,我的问题是是否可以以某种方式在其中实现cookie,所以如果我关闭浏览器然后重新打开它(或者至少用秒表关闭选项卡,不确定是否有区别),计时器将仍然存在运行。

最佳答案

以下是使用 cookie 和秒表的示例:

https://jsfiddle.net/tmonster/00eobuxy/

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

function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 "";
}

Number.prototype.pad = function() {
return ("0" + String(this)).substr(-2);
}

var startTime = new Date();
var isRunning = false;

function tick() {
if (!isRunning) return;
var t = new Date(new Date() - startTime);
document.getElementById("stopwatch").innerHTML = t.getUTCHours().pad() + ":" + t.getMinutes().pad() + ":" + t.getSeconds().pad();
setTimeout(tick, 1000);
}

function CheckIfClockedIn() {
var ct = getCookie("ClockInTime");
if (ct.length == 0) return;
isRunning = true;
startTime = new Date(ct);
tick();
document.getElementById("punchInOut").innerHTML = "Clock out";
}

function PunchInOut() {
if (!isRunning) {
isRunning = true;
startTime = new Date();
tick();
setCookie("ClockInTime", startTime, 1);
document.getElementById("punchInOut").innerHTML = "Clock out";
} else {
isRunning = false;
setCookie("ClockInTime", "", 0);
document.getElementById("stopwatch").innerHTML = "Not clocked in";
document.getElementById("punchInOut").innerHTML = "Clock in";
}
}

关于javascript - 将 cookie 实现到简单的秒表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28391615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com