Mashpoe
Mashpoe

Reputation: 524

JavaScript cookie error

Today I was trying to learn how to use cookies, and it was going pretty well, until I tried to make a cookie save the total amount of seconds you have been on the page, including previous visits. Instead of counting up like 1, 2, 3, it counted like 1, 11, 111, 1111. Here is my code:

<!DOCTYPE html>
<html>
<head>
<script>

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

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

var value = getCookie('value');

window.setInterval(function(){

    value = value + 1;
    document.getElementById("value").innerHTML = value;
    setCookie("value", value, 365);

}, 1000);

</script>
</head>
<body>
<p>
<span id="value">0</span>
</body>
</html>

Upvotes: 2

Views: 356

Answers (1)

Barmar
Barmar

Reputation: 782584

value is a string, so + is concatenation, not addition. Use either:

value++;

(this will convert it to a number so it can increment it)

or

value = parseInt(value, 10) + 1;

Upvotes: 4

Related Questions