0

I am using Date().getTime to measure the duration of a keypress by subtracting the keydown event from the keyup event. However, for keypresses longer than ~500ms, the recorded time appears to return to a lower value.

Here is the JSFiddle http://jsfiddle.net/bdzaorw2/

$(document).ready(function(){

Crafty.init(window.innerWidth,window.innerHeight);
var player = Crafty.e();

//...

function horizontal(){

if(keyboard[38] && !player.jumping){
    player.v.velocity = 5;
    player.jumping = true;
}

if(keyboard[38] && player.jumping){
    var now = new Date();
    if( now.getTime() - keystart[38].getTime() < 500){
        player.v.velocity = 5;
    }
    document.getElementById("p").innerText = now.getTime() - keystart[38].getTime();
}


  setTimeout(horizontal, (frame * 1000) / timeMultiplier);
}


horizontal();


document.body.addEventListener("keyup", function (code) {
    keyboard[code.keyCode] = false;
});

document.body.addEventListener("keydown", function (code) {
    keyboard[code.keyCode] = true;
    var then = new Date();
    keystart[code.keyCode] = then;
});

});

2 Answers2

0

Try Event.timeStamp and see if it makes a difference. Here's one example:

var number = event.timeStamp;

and

<html>
<head>

<title>timeStamp example</title>

<script type="text/javascript">
function getTime(event) {
  document.getElementById("time").firstChild.nodeValue = event.timeStamp;
}
</script>
</head>

<body onkeypress="getTime(event)">

<p>Press any key to get the current timestamp
for the onkeypress event.</p>
<p>timeStamp: <span id="time">-</span></p>

</body>
</html>
risto
  • 1,274
  • 9
  • 11
0

I've seen something wrong in your code: - on keydown you are calculating and recalculating the Date.now() so just changed this part of the code

keyboard[code.keyCode] = true;
var then = new Date();
keystart[code.keyCode] = then;

with this:

var then = new Date();
if(!keyboard[code.keyCode]) { //only if not yet pressed it will ignore everything until keyup
    keyboard[code.keyCode] = true; //start movement
    keystart[code.keyCode] = then; //set time
}

Here is the adapted example: http://jsfiddle.net/bdzaorw2/

atrifan
  • 172
  • 5