1

I've worked through this code and am close to what I want, yet two small details are missing. The function measures elapsed time between two events and stops after 3 runs.

I would like to have the time reset after each keypress event. In my research I found this question: Mesure a Reaction Time in ms on a JSP webpage but it wasn't of much help for the resetting.

Also I would like to change the text of my div every 2 seconds automatically when no key is pressed and get the elapsed time of 2000 then.

Is this possible in some way? I've tried setInterval but didn't succeed.

var t1; var counter=0; var teststim = ["AAA", "BBB", "CCC", "DDD"]; $(function(){ t1 = (new Date()).getTime(); $(document).keypress(function(e){ var t2 = (new Date()).getTime(); var reac = t2 - t1; counter++; if (e.keyCode == 97 || e.keyCode == 108) { $("#stimuli").text(teststim[Math.floor(Math.random() * teststim.length)]); }; if (counter == 3) { confirm("It's over!"); } }); }); 
2
  • "every 2 seconds automatically"... Tried with setInterval ? Commented Mar 20, 2014 at 21:15
  • setInterval seems right to me. Call the function every 2 seconds, and if a key is pressed clear the timer and reset it to 2 seconds. Commented Mar 20, 2014 at 21:15

2 Answers 2

2

This doesn't measure reaction time, but it's a working example of setInterval / clearInterval.

updateText = function(){ $("body").append( $("<p></p>").html(Date())) } timer = setInterval( updateText, 2000 ) $(document).keypress(function(){ clearInterval( timer) $("body").append( $("<p></p>").html("Keypress at " + Date() )) timer = setInterval( updateText, 2000 ) }) 

http://jsfiddle.net/KHaaL/

Sign up to request clarification or add additional context in comments.

2 Comments

thank you. This is great. Any idea where I should invoke my counter? Transferred to your example, I want to count the number of "date prints" on the screen, regardless of whether it was key induced or in the interval. This would make my day...
Fixed the counter myself: just made separate counters for regular runs and key events. This worked. Thanks anyway.
2

Set t1 to the current time after you measure the reaction time.

var reac = t2 - t1; t1 = t2; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.