Skip to content

Instantly share code, notes, and snippets.

@WebInspectInc
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WebInspectInc/0de4b7a02330834f9bb5 to your computer and use it in GitHub Desktop.
Save WebInspectInc/0de4b7a02330834f9bb5 to your computer and use it in GitHub Desktop.
JS localStorage basic caching for a day
// Usage: cache_for_a_day('data_id', <data>);
// If you only provide an ID, it gets
// If you provide both, it checks the date and returns cached data if it's been cached less than a day. Otherwise it sets the new data
function cache_for_a_day(id, data) {
var new_data = {};
var old_data = JSON.parse(localStorage.getItem(id));
if (old_data) {
var cache_date = new Date(old_data.cache_date);
var today = new Date();
if (cache_date.getTime() > today.getTime()) {
// using cache
return old_data.data;
}
}
if (data) {
// saving a cache
var date = new Date();
date.setDate(date.getDate() + 1);
new_data.cache_date = date;
new_data.data = data;
localStorage.setItem(id, JSON.stringify(new_data));
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment