November 2, 2010
How to create a jquery timer that starts on keyup
Question by Josh R
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.
Thanks
Answer by lonesomeday
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
});