使用 setTimeout() 函数从 localStorage 中删除项目

Removing items from localStorage using the setTimeout() function

localStorage 中的 userData 项映射到从服务器传递的 JSON 字符串。 我想要做的是每次 PHP 会话结束时从 localStorage 中删除此项并将 userId 设置为默认值。

variables.js

var userIdDefault = 1;
var sessionDuration = 1440;

if(localStorage.getItem('userData')) {
    var userDataStored = JSON.parse(localStorage.getItem('userData'));
    var userId = userDataStored["userId"];

    var sessionStartTime = parseInt(userDataStored["sessionStartTime"]);
    var sessionStopTime = sessionStartTime + sessionDuration;
}
else {
    var userId = userIdDefault;
}

main.js

$(document).ready(function() {
    if(userDataStored) {
        var timeNow = Math.floor(new Date().getTime() / 1000);
        waitTime = sessionStopTime - timeNow;

        setTimeout(function() {
            console.log('sessionStartTime: ' + sessionStartTime);
            console.log('waitTime: ' + waitTime);
            console.log('timeNow: ' + timeNow);
            console.log('sessionStopTime: ' + sessionStopTime);
        
            localStorage.removeItem("userId");
            var userId = userIdDefault;
        }, waitTime); 
    }
});

浏览器控制台日志:

1st page reload
main.js: sessionStartTime: 1422232761
main.js: waitTime: 1434 main.js: timeNow: 1422232767
main.js: sessionStopTime: 1422234201

2nd page reload
main.js: sessionStartTime: 1422232761
main.js: waitTime: 1416
main.js: timeNow: 1422232785
main.js: sessionStopTime: 1422234201

userDataStored
Object {userId: "23", login: "login2", firstName: "name", lastName: "name", email: "example@mail.com"...}

userId
"23"

该代码不起作用,因为本地存储中没有包含密钥的数据 用户身份。用户 ID 是您存储在本地存储中的 JSON 对象中的键。

var userDataStored = JSON.parse(localStorage.getItem('userData'));
userDataStored.userId = null;
localStorage.setItem('userData', JSON.stringify(userDataStored ));