localStorage content with time stamp to remove itself

早过忘川 提交于 2019-12-22 10:54:12

问题


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/


回答1:


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
            }) );
        }
    };
});


来源:https://stackoverflow.com/questions/16067066/localstorage-content-with-time-stamp-to-remove-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!