1

Was wondering how long it takes to write to document.cookie. Ran into an edge case when setting a cookie and re-directing to another page and the document.cookie was not getting set. Seemed to have different performance on a desktop (Chrome, firefox) vs iphone/tablet (safari)

Seemed to worked correctly in all cases when I added a set timeout of about 500ms

// writing cookie out

   function set_cookie(name, value ) {
        var date =  new Date();
        date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000)); 
        var cookie = name + "=" + value + "; expires=" + date.toGMTString() + ";";
        document.cookie = cookie;

    }

// reading cookie

function read_Cookie(name) {

        var nameEQ = name + "=";
        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, c.length);
            if (c.indexOf(nameEQ) == 0) {
                var cVal = c.substring(nameEQ.length, c.length);
                return cVal;
            }
        }
        return null;
    }

// button click setting cookie and navigation

        $("#goToWebButton").click(function() {
             if ($('#chkDontShow').attr('checked') == 'checked') {
                set_cookie('IgnoreInAppLink','web');
               }
            setTimeout(function(){window.location.href = '';}, 500);
        });

        $("#goToAppButton").click(function() {
          if ($('#chkDontShow').attr('checked') == 'checked') {
                set_cookie('IgnoreInAppLink','app');
            }
            setTimeout(function(){window.location.href = '';},500);

        });
nate_weldon
  • 2,289
  • 1
  • 26
  • 32

1 Answers1

-2

JavaScript is by it's very nature single-threaded therefore the redirect shouldn't be executed until the cookie has been written regardless of how long it takes (almost instantaneous). That said, as pointed out at Is JavaScript guaranteed to be single-threaded? that may not always be the case. To mitigate this you might consider using jQuery's deferred object as such:

function set_cookie(name,value,deferred) { // added deferred argument
    var date =  new Date();
    date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000)); 
    var cookie = name + "=" + value + "; expires=" + date.toGMTString() + ";";
    document.cookie = cookie;
    deferred.resolve();
}

var deferred = $.Deferred();

deferred.done(function() {
    window.location.href = "";
});

$("#goToAppButton").click(function() {
    if ($("#chkDontShow").attr("checked") == "checked") {
        set_cookie("IgnoreInAppLink","web",deferred);
    } else {
        deferred.resolve();
    }
}
Community
  • 1
  • 1
robbymarston
  • 344
  • 3
  • 16
  • 1
    Your usage of `$.Deferred` does not improve anything over OP's code without the timeout. That aside, a function should never take a deferred as an argument, but rather return a promise. – Bergi Oct 20 '14 at 23:46