将 cookie 实现到简单的秒表中

Implementing cookies into simple stopwatch

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

如果您将开始时间(秒表启动时的实际时间值)存储在 cookie 中,那么无论何时从该浏览器打开页面,您都可以从cookie,获取当前时间,计算经过时间并显示经过时间。

然后您可以从那里开始计算时间。

似乎计时器一直是 运行。

这样做的一个不错的功能是,在关闭选项卡时您不必存储任何东西(有时是有问题的)。相反,您只需在秒表启动时存储 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";
    }
}