我试图在使用Mousedown函数的鼠标按钮向下启动计时器时,并在鼠标按钮随鼠标函数启动时停止计时器
这是我得到的代码:
var startTime;
function display() {
// later record end time
var endTime = new Date();
// time difference in ms
var timeDiff = endTime - startTime;
// strip the miliseconds
timeDiff /= 1;
// get seconds
var seconds = Math.round(timeDiff % 100000000);
$(".time").text(seconds);
setTimeout(display, 1);
}
$(canvas).click(function () {
startTime = new Date();
setTimeout(display, 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas height="420" style="background:#e4e1e1" id="canvas" width="540"></canvas>
<div class="time"></div>
您可以在此处使用setInterval
而不是setTimeout
,因为您希望该功能反复触发。但是,无论您使用哪个,您都必须将间隔的返回值分配给变量,以便可以使用clearTimeout
或clearInterval
迟到。
此外,最少的时间将永远无法比较早,大约是9-16毫秒,因此您永远不会发生1毫秒的延迟。
var startTime = null;
var timer = null;
function display() {
// later record end time
var endTime = new Date();
// time difference in ms
var timeDiff = endTime - startTime;
// strip the miliseconds
timeDiff /= 1;
// get seconds
var seconds = Math.round(timeDiff % 100000000);
$(".time").text(seconds);
}
$(canvas).on("mousedown", function () {
startTime = new Date();
timer = setInterval(display, 10);
});
$(canvas).on("mouseup", function () {
clearInterval(timer);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas height="50" style="background:#e4e1e1" id="canvas" width="100"></canvas>
<div class="time"></div>