我正在显示3个按钮,如果我在1秒钟内单击开始和停止按钮,那么它没有显示任何效果,但是如果我多次执行该操作,那么结果应该是没有增加。< / p>
我希望它也显示同时启动和停止按钮之间经过的毫秒数。
var secs = 0;
var mins = 0;
var timer;
var start = 0;
var stop = 0;
function add() {
secs++;
if (secs == 60) {
mins++;
secs = 0;
}
if (mins == 6) {
mins = 0;
secs = 0;
}
display();
}
function startc() {
if (start == 0) {
timer = setInterval(add, 1000);
start = 1;
}
}
function stopc() {
clearInterval(timer);
start = 0;
stop = 1;
}
function clearc() {
secs = 0;
mins = 0;
clearInterval(timer);
display();
if (stop != 1) {
start = 0;
startc();
}
}
答案 0 :(得分:0)
如果要显示单击不同按钮之间经过的毫秒数,那么我认为您不需要这么复杂的代码。 (我使用jQuery。)
let start = 0
let stop = 0
let isRunning = false
$('#start').on('click', function(e) {
if (!isRunning) {
start = Date.now()
isRunning = true
}
})
$('#stop').on('click', function(e) {
if (isRunning) {
stop = Date.now()
display(start, stop)
isRunning = false
}
})
const display = (start, stop) => {
$("#displayms").text(stop - start + ' ms')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="start" class="btn">START</button><br />
<button id="stop" class="btn">STOP</button>
<hr />
<div>MILLISECONDS PASSED: <span id="displayms">0 ms</span></div>