javascript - 在 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 标志用于指示定时器的状态。
解决方案
您的任何方法都不需要static
. 此外,如果您只记录秒数,然后在需要输出时计算分钟数,它会更简单、更容易使用。作为标准,类的名称大写。最后,您可能正在寻找setInterval
,而不是超时。
想想现实世界的计时器。您可以对其进行设置、启动、暂停和停止。停止计时器实际上只是重新启动它并暂停它,它是在创建时设置的,所以让我们Timer
用start
,pause
和or来创建一个。通过使用 1s 超时,这仍然与您在后台的行为相同,但是对于阅读您的代码的人来说,它更清晰、更容易理解:set
stop
reset
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)
}
}
}
推荐阅读
- vue.js - 使用带有外部激活器的 Vuetify 工具提示(v-tooltip)组件(即未包装)
- scala - 你如何处理 Akka Flow 中的 futures 和 mapAsync?
- arrays - 在 URL 变量上递增
- python - 'bg' 和 'background' 之间的标签背景颜色差异
- bash - Asterisk 创建基于呼叫来源发送电子邮件的脚本
- haskell - 如何使用“optparse-applicative”创建和区分全局选项?
- javascript - 立即显示对 HTML5 画布的更改
- php - 在动态 php 样式表中添加 PHP IF 语句
- r - Emacs ESS 在 %>% 后缩进
- time - 天作为时间序列?