moses toh
moses toh

Reputation: 13192

How can I remove local storage after one hour?

My data is object

I save it use local storage javascript like this :

localStorage.setItem('storedData', JSON.stringify(data))

I just want to keep that data for 1 hour. So if it's been more than 1 hour then the data will be removed

I know to remove data like this :

localStorage.removeItem("storedData")

But how can I set it to auto delete after 1 hour?

Upvotes: 11

Views: 66977

Answers (9)

Nandu
Nandu

Reputation: 187

Add the following code in your App.js file, then the localStorage will be cleared for every 1 hour

var hours = 1; // to clear the localStorage after 1 hour
               // (if someone want to clear after 8hrs simply change hours=8)
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);
    }
}

Upvotes: 16

qpaycm
qpaycm

Reputation: 932

Alternatively you can use IndexedDB in WebWorkers. What it basically means is you can create a parallel to your main thread JavaScript program, like this

var worker = new Worker('worker.js');

The advantage is when it finishes its work, and you don't have a reference to it, it gets cleaned up automatically. However, since I'm not fully sure about the above, here is The worker's lifetime from Living Standard

Workers communicate with other workers and with browsing contexts through message channels and their MessagePort objects.

Each WorkerGlobalScope object worker global scope has a list of the worker's ports, which consists of all the MessagePort objects that are entangled with another port and that have one (but only one) port owned by worker global scope. This list includes the implicit MessagePort in the case of dedicated workers.

Given an environment settings object o when creating or obtaining a worker, the relevant owner to add depends on the type of global object specified by o. If o specifies a global object that is a WorkerGlobalScope object (i.e., if we are creating a nested dedicated worker), then the relevant owner is that global object. Otherwise, o specifies a global object that is a Window object, and the relevant owner is the responsible document specified by o. A worker is said to be a permissible worker if its WorkerGlobalScope's owner set is not empty or:

  • its owner set has been empty for no more than a short implementation-defined timeout value,
  • its WorkerGlobalScope object is a SharedWorkerGlobalScope object (i.e., the worker is a shared worker), and
  • the user agent has a browsing context whose Document object is not completely loaded.

Another advantage is you can terminate a worker, like this

worker.terminate();

Also, it is worth mentioning

IndexedDB has built-in support for schema versions and upgrading via its IDBOpenDBRequest.onupgradeneeded() method; however, you still need to write your upgrade code in such a way that it can handle the user coming from a previous version (including a version with a bug).

Upvotes: 1

Dgloria
Dgloria

Reputation: 301

Just add the check in your app to check if the variable exists and then do a check on it. Put a unix timestamp on the variable, and compare that the next time the user visits your site.

Upvotes: 0

atiq1589
atiq1589

Reputation: 2327

I think setTimeout() method will do the trick.

UPDATED:

While setting the value to localStorage also set the time of recording the data.

// Store the data with time
const EXPIRE_TIME = 1000*60*60;
localStorage.setItem('storedData', JSON.stringify({
  time: new Date(),
  data: "your some data"
}));

// start the time out

setTimeout(function() {
    localStorage.removeItem('storedData');
}, EXPIRE_TIME); // after an hour it will delete the data

Now the problem is if user leave the site. And setTimeout will not work. So when user next time visit the site you have to bootstrap the setTimeout again.

// On page load
$(document).ready(function() {
  let userData = JSON.parse(localStorage.getItem('storedData')) || {};
  let diff = new Date() - new Date(userData.time || new Date());
  let timeout = Math.max(EXPIRE_TIME - diff, 0);
  setTimeout(function() {
      localStorage.removeItem('storedData');
  }, timeout);
})

Upvotes: -2

Gabriel Lupu
Gabriel Lupu

Reputation: 1447

This works for a SPA where the browser window doesn't reload on page renders:

Set an expiresIn field in your local storage. On window reload check to see if current time >= expiresIn if true clear localStorage items else carry on You can also do this check whenever your business logic requires it.

Upvotes: 0

Eben Hafkamp
Eben Hafkamp

Reputation: 155

Use cookies instead

Cookies.set('foo_bar', 1, { expires: 1/24 })

Upvotes: 1

Muhammad Akber Khan
Muhammad Akber Khan

Reputation: 757

use setInterval, with setting/pushing expiration key in your local data, check code below.

var myHour = new Date();
myHour.setHours(myDate.getHours() + 1); //one hour from now
data.push(myHour);
localStorage.setItem('storedData', JSON.stringify(data))

function checkExpiration (){ 
    //check if past expiration date
        var values = JSON.parse(localStorage.getItem('storedData'));
    //check "my hour" index here
    if (values[1] < new Date()) {
        localStorage.removeItem("storedData")
    }
}

function myFunction() {
    var myinterval = 15*60*1000; // 15 min interval
    setInterval(function(){ checkExpiration(); }, myinterval );
}

myFunction();

Upvotes: 6

Gaurav Rao
Gaurav Rao

Reputation: 117

You can't use setTimeout().Since you can't guarantee your code is going to be running on the browser in 1 hours. But you can set a timestamp and while returning back just check with Timestamp and clear the storage out based on expiry condition.

Upvotes: 7

Brent Thierens
Brent Thierens

Reputation: 451

You can't. When do items in HTML5 local storage expire? The only thing you can do is set the delete statement in a timeout of 1 hour. This requires the user to stay on your page or the timeout won't be executed.

You can also set an expiration field. When the user revisits your site, check the expiration and delete the storage on next visit as the first thing you do.

Upvotes: 22

Related Questions