unscope
unscope

Reputation: 27

Remove my localstorage

Having the following, local storage script, i'm looking for a way so that after 7 days, the balance will be reset, if balance is = 0. How should i do that?

var balance = localStorage.getItem('balance');

if (balance === null) {
    // Not found, set value from database or wherever you get the value
    balance = 50; // Or whatever value
} else {
    // Convert the retrieved value to a number, since
    // localStorage stores everything as string.
    balance = +balance; 
}

function updateBalance(newBalance) {
        localStorage.setItem('balance', newBalance);
        balance = newBalance;
    }

Upvotes: 0

Views: 48

Answers (1)

terrymorse
terrymorse

Reputation: 7086

You need to store the date along with the balance. Since localStorage only stores strings, you can use JSON to convert your balance + date object to a string. Something like this:

var balanceObj = {
    balance: 0,
    transactionDate: new Date()
};

Store it:

localStorage.balance = JSON.stringify( balanceObj );

Retrieve it:

balanceObj = JSON.parse( localStorage.balance );

Upvotes: 1

Related Questions