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;
});
});
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/