[英]How to make clock stop
I have to create two methods start and stop.我必须创建两个方法启动和停止。 Start method starts displaying current time in console in format 'hh:mm:ss' every second starting from now.
Start 方法从现在开始每秒开始在控制台中以“hh:mm:ss”格式显示当前时间。 Second method stops it.
第二种方法停止它。 I am using clearInterval() to stop it but which argument should I pass there?
我正在使用 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()
}
}
In your run
method, assign the number returned by setInterval
to an attribute:在您的
run
方法中,将setInterval
返回的数字分配给一个属性:
run(){
this.interval = setInterval(() => { ... });
}
Later, in your stop
method, pass that attribute to the clearInterval
fn invocation:稍后,在您的
stop
方法中,将该属性传递给clearInterval
fn 调用:
stop(){
return clearInterval(this.interval);
}
That's how it will know which interval you want to clear.这样它就会知道您要清除哪个间隔。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.