首页 > 解决方案 > 如何让时钟停止

问题描述

我必须创建两个方法启动和停止。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()
  }

}

标签: javascript

解决方案


在您的run方法中,将返回的数字分配给setInterval属性:

run(){
  this.interval = setInterval(() => { ... });
}

稍后,在您的stop方法中,将该属性传递给clearIntervalfn 调用:

stop(){
  return clearInterval(this.interval);
}

这就是它知道您要清除哪个间隔的方式。


推荐阅读