javascript - checking TimeStamp for LocalStorage record -


i have got div dynamic content:

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

and want add content localstorage 50 sec prevent new requests server , if older 50 sec remove , set new content. jquery is:

 $(function(){  function now() {return+new date}  var db = window.db = {    : 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(),         value : value     }) );   }  };  });   $(function() {  // set value ttl of 50 seconds using milliseconds.  db.set( "homenews", $("#news").html(), 50000 );  });   $(function() {  var contentsofnews = db.get("homenews");  $("#news").html(contentsofnews);  }); 

the issue is: adding content localstorage every load should check timestamp , if content added more 50 sec rewrite localstorage data. if less 50 sec nothing. thank help.

please feel free edit fiddle: http://jsfiddle.net/kqmky/1/

thanks million

you check in set function, see if value exists, , check ttl there too

something should suffice:

set : function( key, value, ttl ) {     var entry = json.parse(localstorage.getitem(key)||"0");      if (!entry || (entry.ttl && entry.ttl + entry.now < now())) {          //set new value in local storage      } } 

that way if there no entry set save, or if there entry ttl has passed overwrite it


Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -