import { Injectable } from '@angular/core'; import { Log } from '../utils/log' const log = new Log('Timer'); @Injectable() export class Timer { constructor() {} /** * 创建倒计时 * @param $scope 作用域 * @param name 挂载在$scope下的变量 * @param sep 倒计时分隔符 */ create = ($scope, name?, sep?, pure?) => { name = name || 'countdown'; let timer; return { /** * 实际倒计时执行方法 * @param second 剩余时间(秒) * @param finished 倒计时结束时的回调 */ start: (second, finished) => { $scope[name] = this.secondToTime(second, sep, pure); const count = () => { $scope[name] = this.secondToTime(--second, sep, pure); if(second > 0){ timer = setTimeout(() => { count(); },1000); }else{ if(timer) clearTimeout(timer); if(finished && typeof finished === 'function') finished(); } } count(); return () => { if(timer) clearTimeout(timer); } } } } // 秒转时分秒 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 this.splitSecondToTime(second,sep); } } } // 分割为指定格式 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; } }