Date getTime 为较长的持续时间提供较低的值

Date getTime gives low values for longer durations

我正在使用 Date().getTime 通过从 keyup 事件中减去 keydown 事件来测量按键的持续时间。但是,对于长于 ~500 毫秒的按键,记录的时间似乎 return 到一个较低的值。

这是 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;
});

});

尝试Event.timeStamp,看看是否有所不同。 这是一个例子:

var number = event.timeStamp;

<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>

我发现你的代码有问题: - 在 keydown 上你正在计算和重新计算 Date.now() 所以只是改变了这部分代码

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

有了这个:

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
}

这是改编后的例子: http://jsfiddle.net/bdzaorw2/