tags:

views:

1391

answers:

3

Hi! 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;
    });
});
+1  A: 

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

Andrew Rollings
+7  A: 

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

  • highlight: Aesthetics, determines if the text should be highlighted when the textbox receives focus. Default true
  • wait: The number of milliseconds to wait before the plugin considers that typing has finished. Default 750.
  • captureLength: The minimum amount of characters necessary before allowing the event to fire. Default 2.
  • callback: The function to callback after the user has "finished" typing. Default void

For a live demo of this plugin, check here, or the SO Users Page

Andreas Grech
A: 

Hi Dreas, thanks for pointing me in the right direction. My script now works perfectly :P

you should accept his answer then.
Pim Jager