用js实现计时的代码
时间: 2024-02-13 16:02:31 浏览: 23
以下是用 JavaScript 实现计时的代码:
```javascript
// 获取计时器的 DOM 元素
const timer = document.getElementById("timer");
// 初始化计时器
let seconds = 0;
let timerInterval = null;
// 开始计时
function startTimer() {
timerInterval = setInterval(() => {
seconds++;
timer.innerText = formatTime(seconds);
}, 1000);
}
// 格式化时间
function formatTime(time) {
const minutes = Math.floor(time / 60);
const seconds = time % 60;
return `${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
}
// 停止计时
function stopTimer() {
clearInterval(timerInterval);
seconds = 0;
timer.innerText = "00:00";
}
// 重置计时
function resetTimer() {
stopTimer();
startTimer();
}
// 绑定按钮点击事件
document.getElementById("start-btn").addEventListener("click", startTimer);
document.getElementById("stop-btn").addEventListener("click", stopTimer);
document.getElementById("reset-btn").addEventListener("click", resetTimer);
```
在 HTML 中,需要添加以下元素:
```html
<p id="timer">00:00</p>
<button id="start-btn">Start</button>
<button id="stop-btn">Stop</button>
<button id="reset-btn">Reset</button>
```
这样,就可以在网页上实现一个简单的计时器了。