1

I am trying to make timer start when mouse button is down using mouseDown function and stop timer when mouse button is up with mouseUp function

Here is code which i got:

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>
AESTHETICS
  • 989
  • 2
  • 14
  • 32

1 Answers1

1

You can use setInterval instead of setTimeout here since you want the function to fire repeatedly. But, whichever you use, you must assign the return value of the interval to a variable so that you can stop it late with clearTimeout or clearInterval.

Also, there is a minimum time that a timer will never be able to be called earlier than and it is roughly 9-16 milliseconds, so your delay of 1 millisecond is never going to happen.

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>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71