Search code examples
javascriptcookiessetcookie

javascript counter with cookies doesn't work


I just tried to make a timer with cookies that makes a button only 3 times clickable (I had to do it with cookies cause it refreshes the page in its process), I made this timer but it doesn't work. Nothing on my page changed at all.

The code I have by //something else happens gets executed by the program.

Timer - (or at least what I thought that would work as a timer) :

mailagain.onclick = function () {
    if (typeof getCookie("countIt") !== 'undefined') {
        if (checkCookie("countIt") > 3) {
            // something happens
        } else {
            //something else happens
            var counter = checkCookie("countIt") + 1;
            setCookie("countIt", counter, 1)
        }
    } else {
        setCookie("countIt", 1, 1)
    }
};

Coockie functions :

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

function checkCookie(name) {
    var value = getCookie("name");
    if (value != "") {
        return value;
    }
}

Solution

  • Some issues:

    • When reading the value from the cookie, be aware that it has the string data type. You need to convert it to number before comparing it with another number or adding 1 to it.
    • The function checkCookie is using the wrong (hard-coded) cookie name, but is even not necessary as a function. You can do all that with getCookie.

    Here is a working version:

    mailagain.onclick = function () {
        // make sure to convert to number (unitary plus), or use 0 when it is not a number:
        var counter = (+getCookie("countIt") || 0) + 1;
        setCookie("countIt", counter, 1)
        if (counter > 3) {
            console.log('clicked too many times! (', counter, ')');
        } else {
            console.log('clicked ' + counter + ' number of times.');
        }
    };