在mousedown()函数上启动计时器并在div中显示它

时间:2017-03-06 22:01:48

标签: javascript jquery timer mousedown

我正在尝试使用mouseDown函数在鼠标按钮关闭时启动计时器,并在鼠标按钮启动时使用mouseUp函数停止计时器

这是我得到的代码:



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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您可以在此使用setInterval代替setTimeout,因为您希望重复触发该功能。但是,无论您使用哪种方式,都必须将间隔的返回值分配给变量,以便可以使用clearTimeoutclearInterval来延迟它。

此外,有一个最小的时间,计时器永远不会被调用,而且大约是9-16毫秒,所以你的延迟1毫秒永远不会发生。

&#13;
&#13;
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);
});
&#13;
<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>
&#13;
&#13;
&#13;