As you know, localStorage will not expire by default, and there is no API that can be set to expire. If you want to achieve expiration removal, you need to implement an API by yourself

Implementation approach

Add two methods setCanExpireLocal and getCanExpireLocal to the Storage prototype to set and get values, respectively

The expiration function needs at least three times: save time, value time and validity time

Access timestamps are generated within the function when the function is called with date.now ()

The valid time is passed in when a value is saved

Returns the value if the saved timestamp plus the valid time is less than the current timestamp indicating that it has not expired

Otherwise it will expire, delete the value and return NULL

The implementation code

	// Save the value function
	// Accept three parameters: key, value, and valid days
  Storage.prototype.setCanExpireLocal = (key, value, expire) = > {
  		// Determine whether the validity period passed in is numeric or valid
  		// isNaN is a built-in function of JS to determine if a value is a NaN (non-numeric),
  		// Returns true for non-numeric values and false for numeric values
  		// We can also restrict the validity period to an integer
            if (isNaN(expire) || expire < 1) {
              throw new Error('Validity shall be a valid number')}// 86_400_000 Number of milliseconds in a day. _ is a numeric separator
            let time = expire * 86 _400_000
            let obj = {
                  data: value, / / stored value
                  time: Date.now(), // Save the timestamp
                  expire: time, // Expiration time
            }
            // Note that localStorage cannot store object types directly, nor can sessionStorage
            Json.stringify () needs to be converted to a string first and then converted back to json.parse () as it values
            localStorage.setItem(key, JSON.stringify(obj))
  }

	// Evaluates the function
	// Take a parameter, store the value of the key
Storage.prototype.getCanExpireLocal = key= > {
    let val = localStorage.getItem(key)
    // Return null if there is no value
    if(! val)return val
    // Save to a string, now back
    val = JSON.parse(val)
    // Save timestamp + valid time = expired timestamp
    // If the current timestamp is greater than the expiration timestamp, it is expired, delete the value and return a prompt
    if (Date.now() > val.time + val.expire) {
      localStorage.removeItem(key)
      return 'Value invalid'
    }
    return val.data
  }
      / / value
  Storage.prototype.setCanExpireLocal('test'.'Expire in one day'.1)
       / / value
  Storage.prototype.getCanExpireLocal('test')
Copy the code