import { BaseLifeCycle } from 'lifeCycle'; // 分割为指定格式 export const splitSecondToTime = (second,sep) => { var seps = sep.split('|'); var str = ''; var days = parseInt((second / 60 / 60 / 24).toString()); var hours = parseInt((second / 60 / 60).toString()) % 24; var minutes = parseInt((second / 60).toString()) % 60; var seconds = second % 60; if(seps.length == 3){ // 一般为时分秒 str = (hours > 0 ? (hours + seps[0]) : '') + (minutes > 0 ? (minutes + seps[1]) : '') + (seconds >= 0 ? (seconds + seps[2]) : ''); }else if(seps.length == 4){ //一般为天时分秒 str = (days > 0 ? (days + seps[0]) : '') + (hours > 0 ? (hours + seps[1]) : '') + (minutes > 0 ? (minutes + seps[2]) : '') + (seconds >= 0 ? (seconds + seps[3]) : ''); } return str; } /** * 秒转时分秒 * @param second 当前秒数 * @param sep 分隔符 * @param pure 是否纯输出秒数 * @returns {any} */ export const secondToTime = (second, sep, pure) => { sep = sep || ':'; if(pure){ return second; }else{ if(sep === ':'){ return [ parseInt((second / 60 / 60).toString()), parseInt((second / 60).toString()) % 60, second % 60 ].join(sep) .replace(/\b(\d)\b/g, "0$1"); }else{ return splitSecondToTime(second,sep); } } } export interface countDownOption extends BaseLifeCycle{ sep? // 分隔符 pure?// 是否纯输出秒数 } // == 倒计时 export const countDown = (second, option:countDownOption = {}) => { const { sep, pure, created, updated, destroyed } = option; let timer; let time = secondToTime(second, sep, pure); if(created) created(time); setTimeout(() => { count(); },1000); function count() { time = secondToTime(--second, sep, pure); if(updated) updated(time); if(second > 0){ timer = setTimeout(() => { count(); },1000); }else{ finish(); } } function finish() { if(timer) clearTimeout(timer); timer = null; if(destroyed) destroyed(); } return { // 结束 finish, // 暂停 pause: () => { if(timer) clearTimeout(timer); }, // 恢复 resume: () => { if(timer) count(); } } }