Question

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!");
        }
    });
});
Was it helpful?

Solution

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/

OTHER TIPS

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

var reac = t2 - t1;
t1 = t2;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top