js多功能秒表计时器代码
时间: 2024-07-17 11:00:26 浏览: 187
在JavaScript中,创建一个多功能秒表计时器的代码可以分为几个步骤,包括初始化、开始/停止计时和重置计时。下面是一个简单的例子,使用`setInterval`和`clearInterval`来实现:
```javascript
// 定义一个计时器对象
var stopwatch = {
running: false,
startTime: null,
timerId: null,
seconds: 0,
minutes: 0,
hours: 0,
};
// 开始计时
stopwatch.start = function() {
if (!this.running) {
this.startTime = new Date();
this.running = true;
this.timerId = setInterval(() => {
var now = new Date();
var elapsedTime = now - this.startTime;
this.seconds = Math.floor(elapsedTime / 1000);
this.minutes = Math.floor(this.seconds / 60);
this.hours = Math.floor(this.minutes / 60);
// 如果超过24小时,则重新从0开始
if (this.hours >= 24) {
this.hours = this.hours % 24;
this.minutes = this.minutes % 60;
this.seconds = this.seconds % 60;
}
// 更新显示
console.log(`Hours: ${this.hours}, Minutes: ${this.minutes}, Seconds: ${this.seconds}`);
}, 1000);
}
};
// 停止计时
stopwatch.stop = function() {
if (this.running) {
clearInterval(this.timerId);
this.running = false;
}
};
// 重置计时器
stopwatch.reset = function() {
this.startTime = null;
this.seconds = 0;
this.minutes = 0;
this.hours = 0;
this.running = false;
};
// 示例用法
stopwatch.start(); // 开始计时
// 停止计时时调用stopwatch.stop();
// 重置时调用stopwatch.reset();
阅读全文