开发者

recording durations in milliseconds using jQuery?

开发者 https://www.devze.com 2022-12-14 12:08 出处:网络
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 t

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开发者_C百科 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?


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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消