计数器
刷新继续倒计时
时间校准
添加每次计数的触发函数
结束的触发函数
链式调用
中途停止,不计入总时间
class Clock {
constructor(time, id = "Clock") {
this.id = id;
this.count = time;
this.fnCallBacks = [];
this.end = () => {
console.log("结束了");
};
this.stopTime = null;
this.lastTime = null;
this.setTimeNo = null;
this.default = {
count: time,
stopTime: null,
stopTime: null,
lastTime: null,
setTimeNo: null
};
}
run() {
this.startTime = Number(new Date());
this.stopTime =
this.stopTime || sessionStorage.getItem(`${this.id}_stopTime`);
let cache = Number(sessionStorage.getItem(this.id));
if (this.stopTime) {
cache = this.startTime - Number(this.stopTime) + cache;
sessionStorage.setItem(this.id, cache);
this.stopTime = null;
sessionStorage.removeItem(`${this.id}_stopTime`);
}
const start = () => {
setTimeout(() => {
this.start();
}, 0);
};
if (cache) {
const time = cache - Number(new Date());
if (time <= 0) {
sessionStorage.removeItem(this.id);
sessionStorage.removeItem(`${this.id}_stopTime`);
this.end();
} else {
this.count = Math.ceil(time / 1000);
start();
}
} else {
sessionStorage.setItem(
this.id,
Number(this.startTime) + this.count * 1000
);
start();
}
return this;
}
start() {
for (let fn of this.fnCallBacks) {
fn(this.count);
}
const currentTime = Number(new Date());
let time;
if (this.lastTime) {
time = 2000 - currentTime + this.lastTime;
} else {
time = 1000;
}
console.log("校准", time.valueOf(), this.count);
this.count--;
this.setTimeNo = setTimeout(() => {
this.lastTime = currentTime;
if (this.count > -1) {
this.start();
} else {
this.end();
sessionStorage.removeItem(this.id);
sessionStorage.removeItem(`${this.id}_stopTime`);
console.log("总共耗时", new Date() - this.startTime);
}
}, time);
return this;
}
pushFn(fn) {
this.fnCallBacks.push(fn);
return this;
}
stop(time = 0) {
setTimeout(() => {
clearTimeout(this.setTimeNo);
}, time);
console.log("总共耗时", new Date() - this.startTime);
this.lastTime = null;
this.stopTime = Number(new Date());
sessionStorage.setItem(`${this.id}_stopTime`, this.stopTime);
return this;
}
init() {
clearTimeout(this.setTimeNo);
sessionStorage.removeItem(this.id);
sessionStorage.removeItem(`${this.id}_stopTime`);
for (let i in this.default) {
this[i] = this.default[i];
}
return this;
}
setEnd(fn) {
this.end = fn;
return this;
}
}
var demo = new Clock(60, "test", e => {
console.log(e);
}).run();
复制代码