m4tu5
m4tu5

Reputation: 41

Implementing cookies into simple stopwatch

I have simple stopwatch in javascript, my question is if it is possible to somehow implement cookies in it, so if i close the browser and then reopen it (or at least close the tab with stopwatch, not sure if theres a difference), the timer will be still running.

Upvotes: 0

Views: 167

Answers (2)

Xanderak
Xanderak

Reputation: 58

Here is an example of using cookies with a stopwatch:

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

Upvotes: 1

jfriend00
jfriend00

Reputation: 707696

If you store the start time (as in the actual time of day value the moment the stopwatch was started) in a cookie, then any time you open the page from that browser, you can read the start time from the cookie, get the current time, calculate the elapsed time and show the elapsed time.

You can then count up the time from there.

It will appear that the timer was running the whole time.

A nice feature of doing it this way is that you don't have to store anything when the tab is closed (which is sometimes problematic). Instead, you just store the cookie when the stopwatch is started.

Upvotes: 0

Related Questions