-1

I have a code to calculate how long it takes from mousedown to mouseup. After I click mouse I will know time that needed from previouse moouse up. Everythings work fine, unless for first click. I know it doesn't work because i put startTimeinto mouseup event, we don't do mouseup when the first click right ? any other idea?

Here is the code:

var startTime, endTime;

$(".btn-number").on('mousedown', function () {
    endTime = new Date().getTime();

    if (endTime - startTime < 250) {
        longpress = false;
        console.log('< 250');
    } else if (endTime - startTime >= 300) {
        longpress = true;
        console.log('>= 300');
    }

});

$(".btn-number").on('mouseup', function () {
    startTime = new Date().getTime();
});
Bayu Anggara
  • 287
  • 2
  • 4
  • 13
  • 1
    Try putting `startTime = new Date().getTime();` at the beginning. Like `var startTime = new Date().getTime(), endTime;` – lmgonzalves Sep 24 '15 at 01:35
  • 2
    mousedown happens before mouseup and both occur within a click. Logic here looks backwards – charlietfl Sep 24 '15 at 01:36
  • defining `startTime` in the bigining means calculate `startTime` when the first page loaded, so the first mouseup is calculated from the first page load – Bayu Anggara Sep 24 '15 at 02:15
  • but you aren't defining startTime on page load. Provide a proper description of what you are trying to do and what this will be used for – charlietfl Sep 24 '15 at 02:17
  • The code looks like you are trying to track the time the mouse button is held down (but you have the events reversed.) However, the description of the problem sounds like you are trying to track the time _between clicks_. Which is it? – Evan Davis Sep 24 '15 at 02:43

1 Answers1

4

I am not able to comment, otherwise this answer is just comment worthy, just interchange mouseup and mousedown

var startTime, endTime,i=0;

$(".btn-number").on('mouseup', function () {
    endTime = new Date().getTime();

    if (endTime - startTime < 250) {
        longpress = false;
        console.log('< 250');
    } else if (endTime - startTime >= 300) {
        longpress = true;
        console.log('>= 300');
    }
    console.log('\n' + i++);
});

$(".btn-number").on('mousedown', function () {
    startTime = new Date().getTime();
});

http://jsfiddle.net/g1x9e7xh/

Harshal Carpenter
  • 470
  • 1
  • 9
  • 24