最近在项目中遇到一个倒计时功能,在网上没有找到合适的,就自己写了个方法。贴在这里,权且当个记录。

export const timeRun = (timeStr, callBack) => {
let timeArr = timeStr.split(':');
if (timeArr.length == 2) {//格式 5:00
let minute = timeArr[0];
let second = timeArr[1];
if (second == '00') {
let minuteInt = parseInt(minute);
minuteInt--;
if (minuteInt.toString().length == 1) {
minute = "0" + minuteInt;
} else {
minute = minuteInt.toString();
}
second = "59";
} else {
let secondInt = parseInt(second);
secondInt--;
if (secondInt.toString().length == 1) {
second = "0" + secondInt;
} else {
second = secondInt.toString();
}
} if ((minute == '00' || minute == '0') && (second == '00' || second == '0')) {
callBack();
return "00:00";
} return minute + ":" + second;
} else if (timeArr.length == 3) {//格式 1:00:00
let hour = timeArr[0];
let minute = timeArr[1];
let second = timeArr[2]; if (second == '00') {
if (minute == '00') {
let hourInt = parseInt(hour);
hourInt--;
minute = '59';
hour = hourInt.toString();
} else {
let minuteInt = parseInt(minute);
minuteInt--;
if (minuteInt.toString().length == 1) {
minute = "0" + minuteInt;
} else {
minute = minuteInt.toString();
}
second = "59";
}
} else {
let secondInt = parseInt(second);
secondInt--;
second = second.toString();
}
if ((hour == '00' || hour == '0') && (minute == '00' || minute == '0') && (second == '00' || second == '0')) return hour + ":" + minute + ":" + second;
} else {
console.error("倒计时时间格式错误");
}
}

使用方法如下,其中finished是回调函数:

let time = '05:00';
let timer = setInterval(() => {
time = timeRun(time, finished);
if(time == "00:00" || time == "0:00:00"){
clearInterval(timer);
}
}, 1000);
05-11 14:03