2012-04-20 25 views
2

我想記錄每個擊鍵(以一個鍵開始,'A'鍵)之間的時間(以毫秒爲單位)。 用戶完成他的事情後,他可以提交併檢查每個擊鍵之間的時間。像:Javascript記錄擊鍵計時

1:500 2:300 3:400 4:500 5:100 6:50 7:50 8:25

我相信這是可能的JavaScript,是它?

+1

時間有多準確? http://ejohn.org/blog/accuracy-of-javascript-time/ – Brad 2012-04-20 15:33:54

+0

大約5毫秒。它僅供個人使用,所以我不必支持所有類型的瀏覽器。 – 2012-04-20 15:38:47

+1

[您嘗試過什麼?](http://whathaveyoutried.com) – veeTrain 2012-04-20 16:06:03

回答

2

肯定的:

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陣列具有五個元素(索引從04):

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 

然後循環終止,因爲設置i4觸發終止條件:

= i < times.length - 1 
= 4 < 5 - 1 
= 4 < 4 
= false [i cannot be set to 4 by this loop] 

因此,times[i+1]始終是一個有效索引的元素,因爲i至多是一個小於最大索引。

+0

謝謝。只有最後一次添加的值不能因爲它沒有被刪除而下降到下一個值。 – 2012-04-20 18:18:26

+0

腳本只在我小於times.length - 1時運行,即最後的i索引是長度-2,所以總是有下一個值。 – apsillers 2012-04-20 18:22:32

+0

您之前發佈了關於僅查看五次印刷機的四條記錄的評論:這是預期結果。 *五次按*會在*之間產生*四次*時間間隔*。 – apsillers 2012-04-20 18:27:40