Last active
August 29, 2015 14:15
-
-
Save WebInspectInc/0de4b7a02330834f9bb5 to your computer and use it in GitHub Desktop.
JS localStorage basic caching for a day
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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