Skip to content

Timer

计时器类

配置项

参数类型是否必选默认值参数描述
-----

返回值

类型描述
void-

示例

const timer = new Timer();
timer.start(); // 开始计时
timer.stop(); // 停止计时
const time = timer.getTime('SS', false); // 获取当前计时时间(格式化)

源码

js
export class Timer {
    constructor() {
        this.startTime = null;
        this.elapsedTime = 0;
        this.timerInterval = null;
    }

    // 开始计时
    start() {
        if (!this.timerInterval) {
            this.startTime = Date.now() - this.elapsedTime;
            this.timerInterval = setInterval(() => this.update(), 1000);
        }
    }

    // 停止计时
    stop() {
        clearInterval(this.timerInterval);
        this.timerInterval = null;
    }

    // 重置计时
    reset() {
        this.stop();
        this.elapsedTime = 0;
    }

    // 获取当前计时时间(格式化)
    getTime(format, isPad) {
        return this.formatTime(this.elapsedTime, format, isPad);
    }

    // 更新计时
    update() {
        const currentTime = Date.now();
        this.elapsedTime = currentTime - this.startTime;
    }

    // 格式化时间为 HH:MM:SS 或自定义格式
    formatTime(milliseconds, format = 'HH:MM:SS', isPad = true) {
        const totalSeconds = Math.floor(milliseconds / 1000);
        let hours = Math.floor(totalSeconds / 3600);
        let minutes = Math.floor((totalSeconds % 3600) / 60);
        let seconds = totalSeconds % 60;
        hours = isPad ? this.pad(hours) : hours;
        minutes = isPad ? this.pad(minutes) : minutes;
        seconds = isPad ? this.pad(seconds) : seconds;
        switch (format) {
            case 'HH:MM:SS':
                return `${hours}:${minutes}:${seconds}`;
            case 'MM:SS':
                return `${minutes}:${seconds}`;
            case 'SS':
                return `${seconds}`;
            default:
                return `${hours}:${minutes}:${seconds}`;
        }
    }

    // 补零函数
    pad(number) {
        return String(number).padStart(2, '0');
    }
}