2

I am making a browser game where it is import to save data to keep your progress. This is the code I am using to save each variable:

function autosave() {
  localStorage.setItem("variablename", variablename);
}
setInterval(autosave, 1000);

However, it has come to my attention that browsers such as chrome can only store 50 cookies per domain. Does each variable count as one cookie? If so, how can I work around this.

akopyl
  • 298
  • 2
  • 12

2 Answers2

2

localStorage and cookies are different.

If you're curious about the limits of localStorage check out this question.

akopyl
  • 298
  • 2
  • 12
2

You said 'Cookies' Right? Here is a method from tutorialsrepublic.com



To set Cookies

function setCookie(name, value, daysToLive = undefined) {
    // Encode value in order to escape semicolons, commas, and whitespace
    var cookie = name + "=" + encodeURIComponent(value);
    
    if (typeof daysToLive === "number") {
        /* Sets the max-age attribute so that the cookie expires
        after the specified number of days */
        cookie += "; max-age=" + (daysToLive*24*60*60);
    }
        
    document.cookie = cookie;
}

To get Cookies

function getCookie(name) {
    // Split cookie string and get all individual name=value pairs in an array
    var cookieArr = document.cookie.split(";");
    
    // Loop through the array elements
    for(var i = 0; i < cookieArr.length; i++) {
        var cookiePair = cookieArr[i].split("=");
        
        /* Removing whitespace at the beginning of the cookie name
        and compare it with the given string */
        if(name == cookiePair[0].trim()) {
            // Decode the cookie value and return
            return decodeURIComponent(cookiePair[1]);
        }
    }
    
    // Return null if not found
    return null;
}

And to reassign cookies, just use the same one as set.

setCookie(Name, NewValue, Days)

Example:
Finally, to delete cookies you can use

setCookie(Name, '', 0)

For Localstorage, Go here

Vivaan
  • 141
  • 2
  • 14