Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barnettjw/70e331d9bba33ff811f1 to your computer and use it in GitHub Desktop.
Save barnettjw/70e331d9bba33ff811f1 to your computer and use it in GitHub Desktop.
Is the localStorage Data Stale?
<h1>Is the localStorage Data Stale?</h1>
<h2>Instructions</h2>
<ul>
<li>enter some text</li>
<li>refresh the page</li>
<li>marvel at localStorage magic</li>
<li>wait a few seconds</li>
<li>refresh the page</li>
<li>see if localStorage data is stale</li>
</ul>
<input placeholder="enter some text" autofocus/>
<div id = "timestamp"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>
/* check if data stored in local storage is stale and needs to be refreshed uses moment.js to check if the current time is past the specificed refresh window*/
$(document).ready(function() {
var timestamp;
var refreshUnit = "seconds";
var refreshValue = 15;
/************* function uodateTimestamp() ****************/
function updateTimestamp(){
timestamp = moment();
localStorage.setItem("timestamp", timestamp);
$("#timestamp").text( "Data last updated at: " + moment(localStorage.getItem("timestamp")).format("h:mm:ss a"));
}
/************* function isDataStale() ****************/
function isDataStale(){
// check if timestamp is set
if (localStorage.getItem("timestamp") !== null) {
var storedAt = moment(localStorage.getItem("timestamp"));
var staleAt = moment(storedAt).add(refreshUnit, refreshValue);
if (moment().isAfter(staleAt)){ return true; } //data is stale
}
else { return true;} //no timestamp found refesh the data
}
/************* Main Logic *************/
//on page load update textbox with data from localstorage
if ( localStorage.getItem('text') ) {
if (isDataStale()) { $('input').val("Data is Stale");} //if data is stale, say so
else{ $('input').val(localStorage.getItem('text')); } //otherwise, update textbox from localstorage
}
$('input').on('keyup', function() {
localStorage.setItem('text', $(this).val());
updateTimestamp();
});
});
body { margin: 30px; }
h1 { font-size: 1.25em;}
h2 {
font-size: 1.1em;
font-weight: normal;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment