我想記錄每個擊鍵(以一個鍵開始,'A'鍵)之間的時間(以毫秒爲單位)。 用戶完成他的事情後,他可以提交併檢查每個擊鍵之間的時間。像:Javascript記錄擊鍵計時
1:500 2:300 3:400 4:500 5:100 6:50 7:50 8:25
我相信這是可能的JavaScript,是它?
我想記錄每個擊鍵(以一個鍵開始,'A'鍵)之間的時間(以毫秒爲單位)。 用戶完成他的事情後,他可以提交併檢查每個擊鍵之間的時間。像:Javascript記錄擊鍵計時
1:500 2:300 3:400 4:500 5:100 6:50 7:50 8:25
我相信這是可能的JavaScript,是它?
肯定的:
var times = [];
// add an object with keycode and timestamp
$(document).keyup(function(evt) {
times.push({"timestamp":evt.timeStamp,
"keycode":evt.which})
});
// call this to get the string
function reportTimes() {
var reportString = "";
for(var i = 0; i < times.length - 1; ++i) {
reportString += (i+1) + ": " + (times[i+1].timestamp - times[i].timestamp) + " ";
}
return reportString; // add this somewhere or alert it
}
我說萬一你以後想它的鍵碼;沒有必要爲你確切的問題陳述。從意見的討論
澄清:
的for
循環只到最多times.length - 2
(因爲i
總是嚴格小於times.length - 1
),所以沒有關於times[i+1]
問題是邊界之外陣列。例如,如果你做5個按鍵,並且因此具有times
陣列具有五個元素(索引從0
到4
):
1st pass: times[1].timestamp - times[0].timestamp
2nd pass: times[2].timestamp - times[1].timestamp
3rd pass: times[3].timestamp - times[2].timestamp
4th pass: times[4].timestamp - times[3].timestamp
然後循環終止,因爲設置i
到4
觸發終止條件:
= i < times.length - 1
= 4 < 5 - 1
= 4 < 4
= false [i cannot be set to 4 by this loop]
因此,times[i+1]
始終是一個有效索引的元素,因爲i
至多是一個小於最大索引。
時間有多準確? http://ejohn.org/blog/accuracy-of-javascript-time/ – Brad 2012-04-20 15:33:54
大約5毫秒。它僅供個人使用,所以我不必支持所有類型的瀏覽器。 – 2012-04-20 15:38:47
[您嘗試過什麼?](http://whathaveyoutried.com) – veeTrain 2012-04-20 16:06:03