Reputation: 63
I have this jQuery code that queries an API on a keyup event (via keyterms.php). It works as it is, but I'm trying to figure out how to implement a "pause" so to speak such that it will only do a query after a certain amount of time (say 2sec.) after the last keyup. Any help will be much appreciated. Thanks!
$(document).ready(function() {
$('#loading').hide();
$('#q').keyup(function(){
$('#loading').show();
$.post("keyterms.php", {
q: $('#q').val()
}, function(response){
$('#qResult').fadeOut();
setTimeout("finishAjax('qResult', '"+escape(response)+"')", 400);
});
return false;
});
});
Upvotes: 4
Views: 3770
Reputation: 107950
You can use the jQuery plugin that StackOverflow uses for its Users Page; it's called TypeWatch
It can be applied like such:
<input type="text" id="tb" />
<script>
$("#tb").typeWatch({ highlight: true, wait: 500, captureLength: -1, callback: finished });
</script>
Where in this case, finished
is a callback function (a reference) that will be invoked when the amount of inputted time (in this case, 500ms) pass from the last keyUp event.
Here is a short description of the parameters it takes (it actually takes one parameter, an object, and the properties of it are used as input parameters) :
For a live demo of this plugin, check out the Users Page
Upvotes: 13
Reputation: 14551
Use a setTimeout
to only call the ajax method two seconds after the key is pressed, rather than calling it directly when the key is pressed. I'm not too familiar with the foibles of JQuery as I haven't had a chance to play with it yet, but it should be able to slot in to your method above.
(Note: two seconds is a pretty long time ;) )
Upvotes: 0