想知道写入document.cookie需要多长时间。在设置cookie并重定向到另一个页面并且document.cookie没有设置时,进入边缘情况。似乎在桌面(Chrome,firefox)和iphone /平板电脑(safari)上有不同的性能
当我添加约500毫秒的设置超时时,似乎在所有情况下都能正常工作
//写出cookie
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;
}
//阅读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;
}
//按钮点击设置cookie和导航
$("#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);
});
答案 0 :(得分:-2)
JavaScript本质上是单线程的,因此重定向不应该被执行,直到cookie被写入,无论花多长时间(几乎是瞬时)。也就是说,正如Is JavaScript guaranteed to be single-threaded?所指出的那样并非总是如此。为了缓解这种情况,您可以考虑使用jQuery的延迟对象:
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();
}
}