javascript - 如何让时钟停止
问题描述
我必须创建两个方法启动和停止。Start 方法从现在开始每秒开始在控制台中以“hh:mm:ss”格式显示当前时间。第二种方法停止它。我正在使用 clearInterval() 来阻止它,但我应该在那里传递哪个参数?
class Clock {
constructor(){
this.date = new Date()
this.hours = this.date.getHours()
this.minutes = this.date.getMinutes()
this.seconds = this.date.getSeconds()
}
run(){
setInterval(()=>{
this.seconds+= 1
if (this.seconds >= 60){
this.minutes++
this.seconds= 0
}
if (this.minutes >= 60){
this.hours++
this.minutes=0
}
if (this.hours >= 24){
this.hours = 0
}
console.log(`${this.hours}:${this.minutes}:${this.seconds}`)
}, 1000)
}
stop(){
return clearInterval()
}
}
解决方案
在您的run
方法中,将返回的数字分配给setInterval
属性:
run(){
this.interval = setInterval(() => { ... });
}
稍后,在您的stop
方法中,将该属性传递给clearInterval
fn 调用:
stop(){
return clearInterval(this.interval);
}
这就是它知道您要清除哪个间隔的方式。
推荐阅读
- video - FFMPEG:修复低运动区域的口吃
- google-cloud-platform - 谷歌云计算负载平衡和自动缩放信息不是为系统管理员类型编写的
- python - PyQT 无法跨 QWizardPage 传递文件名
- xml - 如何设计一个基于其他元素限制元素使用的 XSD
- windows-10 - 将本地安装权限授予角色
- c# - 如何在 Xamarin.iOS 中使用 System.IO.FileStream?
- fortran - Fortran中数组维度中5:8的含义是什么?
- combobox - 将选定值传递到第二个组合框以过滤可用值
- django - 如何修复 django appendslash 运行时错误?
- mysql - 消除 GROUP_CONCAT 中的重复行