localStorage 内容带有时间戳以自行删除

2024-02-08

我想要一个本地存储内容的计时器。

例如我有一个动态更新的 DIV

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

并设法使用以下代码将其作为 html 块添加到 localStorage:

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

我需要向 localStorage["homeNews"] 添加一个时间戳和一个片段,该片段将在 5 分钟后通过检查当前时间和 localStorage 的时间戳将其删除。

小提琴在这里:http://jsfiddle.net/Rn4NC/ http://jsfiddle.net/Rn4NC/


带有 TTL 生存时间的本地存储内容时间戳可自行删除

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

目标是提供一个易于使用的接口,可以根据程序员提供的时间提取不太旧的数据。这是简单的界面:

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

这是示例用例,接下来是支持 TTL 的接口定义:

具有 TTL 接口定义的本地存储。

这是接口逻辑db用法并在上面的示例中使用。结帐JSFiddle http://jsfiddle.net/Rn4NC/3/完整用法的示例。

$(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
            }) );
        }
    };
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

localStorage 内容带有时间戳以自行删除 的相关文章

随机推荐