qqruza
qqruza

Reputation: 1417

localStorage content with time stamp to remove itself

I would like to have a timer for content in localStorage.

For example I have got a dynamically updated DIV

<div id="news"><p>test</p></div>

And managed to add it as html block to localStorage by using this code:

$(function() {
   localStorage["homeNews"] = JSON.stringify($("#news").html());
});
$(function() {
   if (localStorage["homeNews"] != null) {
       var contentsOfNews = JSON.parse(localStorage["homeNews"]);    
      $("#news").html(contentsOfNews);
 } 
});

I need to add a time stamp to the localStorage["homeNews"] and a snippet which will remove it after 5 minutes by checking the current time and the time stamp of my localStorage.

The fiddle is here: http://jsfiddle.net/Rn4NC/

Upvotes: 3

Views: 6401

Answers (1)

Stephen Blum
Stephen Blum

Reputation: 6834

LocalStorage Content Timestamp with TTL Time To Live to Remove Itself

JSFiddle: http://jsfiddle.net/Rn4NC/3/

The goal is to provide an interface that is easy to use to pull in data that is not too old based on a time supplied by the programmer. Here is the simple interface:

Usage of DB Example with TTL

HTML

<div id="news"><p>test</p></div>

JavaScript

$(function() {
    // Set Value with TTL of 5 Seconds using Milliseconds.
    db.set( "homeNews", $("#news").html(), 5000 );
});

$(function() {
    // Get Value
    var contentsOfNews = db.get("homeNews");

    // Show Value
    $("#news").html(contentsOfNews);
});

That's the example usage case, next is the interface definition with TTL support:

Local Storage with TTL Interface Definition.

Here is the interface logic for db usage and is used in the example above. Checkout the JSFiddle example for the full usage.

$(function(){
    function now () {return+new Date}
    var db = window.db = {
        get  : function(key) {
            var entry = JSON.parse(localStorage.getItem(key)||"0");
            if (!entry) return null;
            if (entry.ttl && entry.ttl + entry.now < now()) {
                localStorage.removeItem(key);
                return null;
            }
            return entry.value;
        },
        set : function( key, value, ttl ) {
            localStorage.setItem( key, JSON.stringify({
                ttl   : ttl || 0,
                now   : now(),
                value : value
            }) );
        }
    };
});

Upvotes: 5

Related Questions