Click here to Skip to main content
15,897,891 members
Please Sign up or sign in to vote.
1.80/5 (2 votes)
See more:
Hello,
I want to automatic clear localStorage after 24 hours.
I was store starting time in localStorage.

Can Anybody help me OR give me hint ...
Please

What I have tried:

i was try to do this setInterval through but i was get failure
Posted
Updated 23-Apr-16 8:53am

You don't. Since you can't guarantee your code is going to be running on the browser in 24 hours there is no way to do this on a schedule.

What you can do however is tag your data with a datetime stamp when you write it to storage. When you go get the storage data back, check the timestamp. If it's more than 24 hours old, clear the storage or just don't use the data.
 
Share this answer
 
 
Share this answer
 
You cannot, no matter what you do. The local storage is local. At the moment of clean-up, the page using this storage may not be open, the user may not run the browser at all.

First of all, you need to think of using sessionStorage instead of localStorage: Window.sessionStorage — Web APIs | MDN[^].

But it's possible then you want to keep some data between session. Then do exactly that. The only problem is that localStorage, in contrast to sessionStorage is permanent, so, you potentially contaminate the local storage area. What to do? To answer, I need to know your requirements. Your 24-hour rule have no justification at all. If you have such justification, you need to explain it, but there is no a way to implement it as you formulated it, and it makes no sense at all. Of course you can clear the local data on session start, but depending on current time. I have no idea why would you need that. The simplest reasonable design would be giving the user explicit button "Clear local data". This button may appear depending on some conditions, including timing, or whatever you want.

Another approach is using session storage all the session time. When a user is about to close the session, you can copy session data to the local data. One little suggestion: do it only with the user consent.

—SA
 
Share this answer
 
v2
Comments
Member 12479831 25-Apr-16 4:02am    
Thank you very much for ersponse
Sergey Alexandrovich Kryukov 25-Apr-16 9:33am    
If you think about it, you will understand that this is a solution, not just response. Are you going to accept it formally?
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900