带时间戳的localStorage内容可自行删除 [英] localStorage content with time stamp to remove itself

查看:164
本文介绍了带时间戳的localStorage内容可自行删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为localStorage中的内容设置一个计时器.

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

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

For example I have got a dynamically updated DIV

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

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

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

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

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.

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

推荐答案

带有TTL生存时间的LocalStorage内容时间戳自我删除

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:

<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支持的接口定义:

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

这是db使用的接口逻辑,在上面的示例中使用.查看 JSFiddle 示例以获取完整用法.

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

这篇关于带时间戳的localStorage内容可自行删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆