Question

I have this code

$(document).ready(function () {
    var d = new Date();
    var newMinutes = d.getTimezoneOffset();

    var storedMinutes = getCookieValue("tzom");

    if (newMinutes != storedMinutes) {
        setCookie("tzom", newMinutes);

        alert("new" + newMinutes);
        alert("stored" + storedMinutes);

        document.location.reload(true);
    }
});

What I'm trying to do here is check a timezone value in a cookie to see if it is different to the current timezone set by the user. This will happen if I user comes to the site and changes their timezone and then goes to another page. If there is a difference then I set the cookie with the new value and reload the page. The problem is that when I reload the page it still shows that there is a difference in the timezones and so the page reloads in an infinite loop. If I am somehow able to click on a different page during this infinite loop then the looping stops.

In fact, what I have noticed, by taking out the reload, is that after changing my timezone, if I click on a page the timezone is reported to be different, if I then click on a second page the timezone still is reported to be different and it is only on the third page click that there is no reporting of the cookies being different.

What is wrong here?

EDIT

Rest of the code is here

function getCookieValue(c_name) {
    var c_value = document.cookie;
    var c_start = c_value.indexOf(" " + c_name + "=");
    if (c_start == -1) {
        c_start = c_value.indexOf(c_name + "=");
    }
    if (c_start == -1) {
        c_value = null;
    }
    else {
        c_start = c_value.indexOf("=", c_start) + 1;
        var c_end = c_value.indexOf(";", c_start);
        if (c_end == -1) {
            c_end = c_value.length;
        }
        c_value = unescape(c_value.substring(c_start, c_end));
    }
    return c_value;
}

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}
Was it helpful?

Solution

Your setCookie function takes 3 parameters, not 2.

Try changing your code into this:

if (newMinutes != storedMinutes) {
    setCookie("tzom", newMinutes,365); //cookie will persist for 365 days

    alert("new" + newMinutes);
    alert("stored" + storedMinutes);

    setTimeout("document.location.reload(true)",1000);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top