Reprinted (localStorage set the expiration time)

Address reprint: https://blog.csdn.net/zhaoxiang66/article/details/86703438

class Storage{

constructor (name) {
this.name = 'Storage';
}
// set the cache
the setItem (the params) {
the let obj = {
name: '',
value: '',
Expires: "",
the startTime: new new a Date () the getTime. () // record when the value stored in the buffer, millisecond
}
the let Options = {};
// obj and passed in the params combined
Object.assign (Options, obj, params);
IF (options.expires) {
// If options.expires set then
// to options.name as key, options to put the value
localStorage.setItem (options.name, the JSON.stringify (Options));
} the else {
// If not set options.expires , it is determined what type of value
the let type = Object.prototype.toString.call (options.value);
// if the value is an array type of object or objects, on the first turn with JSON.stringify, another deposit into
IF (Object.prototype.toString.call (options.value) == '[Object Object]') {
options.value the JSON.stringify = (options.value);
}
IF (Object.prototype.toString.call (Options. value) == '[Object the Array]') {
options.value the JSON.stringify = (options.value);
}
localStorage.setItem (options.name, options.value);
}
}
// get cache
getItem (name) {
the let = localStorage.getItem Item (name);
// try to get the first object into json form for
the try {
Item = the JSON.parse (Item);
} the catch (error) {
// If not not json string, return directly
Item Item =;
}
// startTime if the value of the set dead time described
IF (item.startTime) {
the let new new DATE = a Date () the getTime ().;
// when the value of the time taken by subtracting the deposit immediately, compared with item.expires, if expired is larger than, smaller than or equal to if not timed
IF (DATE - item.startTime> item.expires) {
// cache expires, clearing the cache, returns to false
localStorage.removeItem (name);
return to false;
} the else {
// cache has not expired, the return value
return item.value;
}
} the else {
// If no expiration time, return the value directly
return Item;
}
}
// buffer removed
the removeItem (name) {
localStorage.removeItem (name);
}
// remove all buffer
Clear () {
localStorage.clear ();
}
}

 

 

Normal call

let storage = new Storage();

Storage . the setItem ( {name : "name" , value : "San Lin distal" } )

 

Adding time to failure

var asd = new Storage();

ASDs. setItem ({

        name:"name",
        value: "Ha ha ha ha ha ha ha"
        expires: 5000 @ 5 seconds Effectiveness
    })

 

 

 

Guess you like

Origin www.cnblogs.com/kaijiangyugty/p/11894527.html