views:

54

answers:

1

I am building an AJAX page that when the user clicks a box, it sends an ajax request and returns a result. This is a very simple game. The users repeatedly click the box, and I need to record how much time has elapsed between each click with a precision of milliseconds. So with my request actually, I will be sending the elapsed time since the last request and storing it in a database or session.

Javascript does have a timer that is precise in ms, right? So does jQuery make this task of keeping a time between clicks easy?

+2  A: 

You don't need jQuery for this. To get the time on the user's machine in milliseconds:

var nowInMilliseconds = new Date().getTime();

And so to compare two times, just subtract the start time from the end time, and that's the difference in milliseconds.

Example:

(function() {
    var firstClick;

    function clickHandler() {
        var now, duration;

        now = new Date().getTime();
        if (!firstClick) {
            // Remember the time of the first click
            firstclick = now;
        }
        else {
            // Second click; how long as it been?
            duration = now - firstClick;

            // Reset so we're waiting for the first click again
            firstClick = undefined;

            // ...send your Ajax data to the server...
        }
    }

    function pageLoad() {
        $('#button').click(clickHandler);
    }

    window.onload = pageLoad; // or jQuery.ready() or whatever
})();

(The outer function is just for scoping, so we don't create unnecessary global symbols.)

T.J. Crowder
Thanks, or in my case, subtract it from the last time to get the difference between events. I'll probably wrap it with jQuery event handling still.
tkotitan
You subtract the first time from the second, not the second from the first. Otherwise you end up with a negative number. :-)
T.J. Crowder
Oh now that's funny, we *both* said it backward. I've fixed my answer.
T.J. Crowder
Shorter alternative to `new Date().getTime()`: `+new Date`
J-P
@J-P: LOL! I actually typed a parenthetical about that (e.g., as a "l33t" alternative but needing a big comment explaining it -- such as the one in Google Closure), but then decided it was too much information.
T.J. Crowder