0

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;
    }
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
unscope
  • 27
  • 7
  • use something to indicate the start time, e.g. set in a cookie or in localstorage. if 7 days has passed when you next access the data, reset it as you need to. – dewd Feb 22 '16 at 18:42
  • According to [this answer](http://stackoverflow.com/questions/2326943/when-do-items-in-html5-local-storage-expire), you do not have control over localStorage expiration -- that's up to the user. You'll have to set an expiring cookie instead. – Sterling Archer Feb 22 '16 at 18:42
  • @SterlingArcher I think the OP isn't worried about localStorage expiration, but with tracking of the latest transaction date. – terrymorse Feb 22 '16 at 18:53

1 Answers1

1

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 );
terrymorse
  • 6,771
  • 1
  • 21
  • 27