Reputation: 10571
I am running a script and I am using a meta refresh
as it could stop due to internet connection or server downtimes or anything:
<meta http-equiv="refresh" content="30">
The script requires a starting variable, this will update every time the scripts runs, so I want to save the latest value for that variable in local storage but by putting it this way, the value will always be overwritten to the starting value
var myId = 47911111;
localStorage.setItem('titles', myId);
Upvotes: 2
Views: 11248
Reputation: 764
Assuming localStorage is available and I understood your issue:
// first declare a variable but don't assign a value
var myId;
// then check whether your localStorage item already exists ...
if (localStorage.getItem('titles')) {
// if so, increase the value and assign it to your variable
myId = parseInt(localStorage.getItem('titles')) + 1;
// and reset the localStorage item with the new value
localStorage.setItem('titles', myId);
} else {
// if localStorage item does not exist yet initialize
// it with your strat value
localStorage.setItem('titles', 1);
// and assign start value to your variable
myId = paresInt(localStorage.getItem('titles'));
}
console.log(myId);
Now each time the page loads the code checks whether there is a localStorage item "titles".
If so, the value of "titles" is increased by 1 and the resulting value is assigned to "myId".
If the localStorage item is not there yet it's initialized with the start value and the start value is assigned to "myId" as well.
Note that localStorage keys and values are always strings and that an integer value is always converted to a string.
Upvotes: 1
Reputation: 6143
First check if your browser supports local storage like this (local storage will persist across page refreshes unlike sessionStorage)
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
// Store value
localStorage.setItem("keyName", variable);
// Retrieve value from local storage and assign to variable
var myId = localStorage.getItem("keyName");
} else {
// Sorry! No Web Storage support..
}
Upvotes: 0