首页 > 解决方案 > 在 javascript 中设置暂停/恢复定时器

问题描述

有没有办法创建一个“计时器”(或秒表)类,使用这个类创建的计时器可以在触发事件时暂停和恢复,例如单击按钮?

我尝试创建类并使用它创建计时器对象,但计时器一旦启动就无法暂停。

我尝试创建此类:

class countdown {
    constructor(min, sec) {
        this.mins = min;
        this.secs = sec;
        this.handler = 0;
    }

    static setTimer(x,minfield,secfield) {
        this.handler = setTimeout(() => {
            if (x.mins == 0 && x.secs == 0) {
                clearTimeout();
            } else {
                if (x.secs == 0) {
                    x.mins -= 1;
                    x.secs = 59;
                } else {
                    x.secs -= 1;
                }
            }

            this.updateTimer(x,minfield,secfield);
            this.setTimer(x,minfield,secfield)
        }, 1000)
    }

    static updateTimer(x,minfield, secfield){
        document.getElementById(minfield).innerHTML = x.mins;
        document.getElementById(secfield).innerHTML = x.secs;
    }

    static stopTimer(x,minfield,secfield) {
        // document.getElementById(minfield).innerHTML = x.mins;
        // document.getElementById(secfield).innerHTML = x.secs;
        clearTimeout(x.handler);
    }
}

用法:

    let countdown1 = new countdown(15,0);
    let countdown_act = false;
    document.getElementById('button').addEventListener( 'click', () => {
            if (!countdown_act) {
                countdown.setTimer(countdown1, 'ctdwn-mins', 'ctdwn-secs');
                countdown_act = true;
            } else {
                countdown.stopTimer(countdown1, 'ctdwn-mins', 'ctdwn-secs');
                countdown_act = false;
            }
            console.log(countdown_act);
        }
    )

countdown_act 标志用于指示定时器的状态。

标签: javascripttimersetintervalclearinterval

解决方案


您的任何方法都不需要static. 此外,如果您只记录秒数,然后在需要输出时计算分钟数,它会更简单、更容易使用。作为标准,类的名称大写。最后,您可能正在寻找setInterval,而不是超时。

想想现实世界的计时器。您可以对其进行设置、启动、暂停和停止。停止计时器实际上只是重新启动它并暂停它,它是在创建时设置的,所以让我们Timerstart,pause和or来创建一个。通过使用 1s 超时,这仍然与您在后台的行为相同,但是对于阅读您的代码的人来说,它更清晰、更容易理解:setstopreset

class Timer {
    constructor(seconds, callback) {
        this.originalTime = seconds;
        this.remainingTime = seconds;
        this.timeout = null;
        this.callback = callback; // This is what the timer does when it ends
    }

    start() {
        this.timeout = setInterval(() => {
            this.remainingTime -= 1; // Remove a second from the timer
            if(this.remainingTime === 0) {
                this.callback(); // Run the callback function
                this.stop(); // Stop the timer to prevent it from counting into the negatives
            }
        }, 1000);
    }

    pause() {
        clearInterval(this.timeout);
    }

    stop() {
        this.pause();
        this.remainingTime = this.originalTime; // Reset the time
    }

    setTime(seconds) {
        this.originalTime = seconds; // Set a new time
        this.stop(); // Have to restart the timer to account for the new time
    }

    get remaining() {
        return {
            seconds: this.remainingTime % 60,
            minutes: Math.floor(this.remainingTime / 60)
        }
    }
}

推荐阅读