Josh R
Josh R

Reputation: 1295

How to create a jQuery timer that starts on keyup

I am using jQuery 1.4. I want create the timer which starts on keyup event and resets on key press event. I want to use $.ajax request to send the time interval to the server. All I could find was countdown timers.

I appreciate any help.

Upvotes: 2

Views: 905

Answers (2)

lonesomeday
lonesomeday

Reputation: 237845

You can do this very simply by comparing timestamps using native Javascript functions -- no jQuery necessary for the timing logic:

var start, end, interval;

$('form' /*or whatever selector*/).keydown(function() {
    start = new Date();
}).keyup(function() {
    end = new Date();

    interval = end.getTime() - start.getTime(); // interval in milliseconds

    // do your AJAX here
});

Upvotes: 2

Will Vousden
Will Vousden

Reputation: 33358

Try using a Date object. Instantiate one on key down, and then another on key up and compare the two to find the time interval. This question has more detail.

Upvotes: 0

Related Questions