var SimpleCache = function() {
_this = this;
_this.map = {};
// 緩存
this.add = function(key, value) {
_this.map[key] = value;
};
this.addExp = function(key, value, timeout) {
_this.map[key] = value;
setTimeout(function() {
_this.del(key);
},
timeout)
};
this.getValue = function(key) {
if (_this.isExt(key)) {
return _this.map[key];
}
return null;
};
this.getAll = function() {
return _this.map;
};
this.del = function(key) {
if (_this.isExt(key)) {
delete _this.map[key];
}
};
this.updata = function() {
if (!_this.isExt(key)) {
return;
}
_this.map[key] = value;
};
this.isExt = function(key) {
if (!_this.map[key]) {
return false;
}
return true;
};
}
一個帶過期的緩存
let sc = new SimpleCache();
sc.add("name","Tim");
console.log(sc.getValue("name"));
sc.addExp("names","Tim1",5000);
setTimeout(function(){
console.log(sc.getValue("names"));
},2000)
setTimeout(function(){
console.log(sc.getValue("nanamesme"));
},6000)