Skip to content

Instantly share code, notes, and snippets.

@shaik2many
Created July 20, 2016 14:07
Show Gist options
  • Star 48 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save shaik2many/039a8efe13dcafb4a3ffc4e5fb1dad97 to your computer and use it in GitHub Desktop.
Save shaik2many/039a8efe13dcafb4a3ffc4e5fb1dad97 to your computer and use it in GitHub Desktop.
set timeout for localStorage or sessionStorage
http://apassant.net/2012/01/16/timeout-for-html5-localstorage/
var hours = 24; // Reset when storage is more than 24hours
var now = new Date().getTime();
var setupTime = localStorage.getItem('setupTime');
if (setupTime == null) {
localStorage.setItem('setupTime', now)
} else {
if(now-setupTime > hours*60*60*1000) {
localStorage.clear()
localStorage.setItem('setupTime', now);
}
}
@CHARITH1995
Copy link

this is a easy way..

@bharathbommidala
Copy link

Well, working exactly what I needed !!

@ghonchesefidi
Copy link

Worked well. Thanks

@steffanhalv
Copy link

steffanhalv commented Nov 4, 2019

Thank you :)

ES6 conversion:

// Clear on startup if expired
let hours = 2
let saved = localStorage.getItem('saved')
if (saved && (new Date().getTime() - saved > hours * 60 * 60 * 1000)) {
  localStorage.clear()
}
// Increase expiration time after save
localStorage.setItem('saved', new Date().getTime())

@harshit-deepsource
Copy link

Thanks a lot !!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment