Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keyup Event After a Time Interval

Tags:

jquery

ajax

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;
    });
});
like image 495
user47947 Avatar asked Dec 13 '22 05:12

user47947


1 Answers

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 out the Users Page

like image 170
7 revs, 3 users 80% Avatar answered Dec 17 '22 22:12

7 revs, 3 users 80%