实现饼干到简单的秒表

问题描述:

我在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"; 
    } 
}