用JavaScript实现电子秒表计时器
时间: 2023-06-04 13:08:45 浏览: 132
使用javascript实现的计时器秒表
4星 · 用户满意度95%
好的,可以使用JavaScript实现电子秒表计时器。以下是示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>秒表计时器</title>
</head>
<body>
<h1>秒表计时器</h1>
<p id="timer">00:00:00:000</p>
<button onclick="start()">开始</button>
<button onclick="stop()">停止</button>
<button onclick="reset()">复位</button>
<script>
var startTime, endTime, elapsed, timerInterval;
var minutes, seconds, milliseconds, mseconds;
var timer = document.getElementById("timer");
function start() {
startTime = new Date();
timerInterval = setInterval(function() {
endTime = new Date();
elapsed = endTime.getTime() - startTime.getTime();
mseconds = elapsed % 1000;
elapsed -= mseconds;
elapsed /= 1000;
minutes = Math.floor(elapsed / 60);
seconds = Math.floor(elapsed % 60);
milliseconds = mseconds.toString().substring(0, 3);
if(minutes < 10) minutes = "0" + minutes;
if(seconds < 10) seconds = "0" + seconds;
timer.innerHTML = minutes + ":" + seconds + ":" + milliseconds;
}, 1);
}
function stop() {
clearInterval(timerInterval);
}
function reset() {
timer.innerHTML = "00:00:00:000";
clearInterval(timerInterval);
}
</script>
</body>
</html>
```
可以将以上代码保存为 HTML 文件,用浏览器打开后即可使用。
阅读全文