Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

CHARITH1995 commented Nov 9, 2018

this is a easy way..

@bharathbommidala
Copy link

bharathbommidala commented Feb 10, 2019

Well, working exactly what I needed !!

@ghonchesefidi
Copy link

ghonchesefidi commented Sep 25, 2019

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

harshit-deepsource commented Feb 13, 2021

Thanks a lot !!

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