用户:
yh12i31查看:9 回复:4 评论:9 创建时间:2024-01-27T16:25:51
以下为定义:
/**
* 计时器
*/
class Timer {
/**
* 初始化
* @param {Number} length 长度(ms)
* @param {Number} [step] 每次循环间隔,默认50(ms)
* @param {{ func:Function,args:*[] }} endFuncData 结束时调用该函数
* @param {{ func:Function,args:*[] }} [stepFuncData] 每一次循环调用一次该函数,默认空
*/
constructor(
length, step = 50,
endFuncData, stepFuncData={ func: ()=>{}, args: [] }
) {
this.length = length;
this.step = step;
this.count = -1;
this.finished = false;
this.endFuncData = endFuncData;
this.stepFuncData = stepFuncData;
};
/**
* 运行函数
* @param {{ func:Function,args:*[] }} funcData 需要运行的函数数据
* @param {Array} otherArgs 其他参数
*/
async runFunc(funcData, ...otherArgs) {
const func = funcData.func;
const args = funcData.args;
return func(...args.concat(otherArgs)) ;
};
/**
* 设置时间
* @param {Number} startTime 开始时间(ms)
*/
setTime(startTime) {
this.startTime = startTime;
this.currectTime = this.startTime;
this.endTime = this.startTime + this.length;
this.loop = undefined;
};
/**
* 开始计时
*/
start() {
this.setTime(new Date().getTime());
this.loop = setInterval(() => {
if (this.currectTime >= this.endTime) {
clearInterval(this.loop);
this.runFunc(this.endFuncData, this.count);
} else {
this.currectTime += this.step;
this.count++;
this.runFunc(this.stepFuncData, this.count);
};
}, this.step);
};
/**
* 结束计时
*/
end() {
this.currectTime = this.endTime;
clearInterval(this.loop);
this.finished = true;
this.runFunc(this.endFuncData, this.count);
this.count = 0;
};
/**
* 暂停计时
*/
pause() {
clearInterval(this.loop);
};
/**
* 继续计时
*/
resumed() {
if (this.finished) {
return;
} else if (this.currectTime >= this.endTime) {
this.end();
return;
};
this.loop = setInterval(() => {
if (this.currectTime >= this.endTime) {
clearInterval(this.loop);
this.runFunc(this.endFuncData, this.count);
} else {
this.currectTime += this.step;
this.count++;
this.runFunc(this.stepFuncData, this.count);
};
}, this.step);
};
};
以下为用法:
// 计时器结束时调用
const endFuncData = {
func: (name) => {
console.log(`@${name} 到了终点`);
},
args: ["吉吉"] // 函数参数
};
// 计时器每一次循环时调用
const stepFuncData = {
func: (name, i) => { // 参数i可填可不填,表示走了第几步(i从0开始计数)
console.log(`@${name} 已经走了${i + 1}步`);
},
args: ["吉吉"] // 函数参数
};
// 计时器本体
const timer = new Timer(
5000, // 总时长
1000, // 每一次循环时长
endFuncData, // 结束时调用该函数
stepFuncData // 每一次循环调用该函数
);
(async function () {
// 开始计时
timer.start();
// 两秒后停止
await sleep(2000);
timer.pause();
console.log("暂停走路");
// 一秒后继续
await sleep(1000);
timer.resumed();
console.log("继续走路");
})();
里面有很多地方写的不好,望大佬轻喷🥲