Set localStorage expiration time

Set localStorage expiration time

1. Set up the cache

     var nowTime = new Date().getTime();
     var data = {
    
     value: val, expirse: nowTime + 30000 }//设置30秒过期
     window.localStorage.setItem(key, JSON.stringify(data))

2. Get the cache

     var data = JSON.parse(window.localStorage.getItem(key));
      if (data !== null) {
    
    
          if (data.expirse != null && data.expirse < new Date().getTime()) {
    
    
            window.localStorage.removeItem(key)
          } else {
    
    
              return data.value
          }
      }
      return null

Guess you like

Origin blog.csdn.net/qq_39367226/article/details/109508678