Take action after user stop typing with Jquery

3

I'm doing a search Suggest where after the user types at least 4 letters in the input it does via Ajax the search with the suggestions to the user. But currently after the user has entered the first 4 letters of the word a new Ajax request is made to each letter entered and I would like Ajax requests to be made only after the user stops typing in the input. Follow the source:

 <script type="text/javascript">
     (function(){
          'use strict';

          $('#search').keyup(function(){
               var $this = $(this);
               var valueSeach = $this.val()

               if(valueSeach.length >= 4){
                   $.ajax({
                      url: "consulta.php",
                      dataType: "json",
                      data: {
                          acao: 'autocomplete',
                          parametro: valueSeach
                      },
                      success: function(data) {
                          response(data);
                      }
                  });
               }                                                        
          });
      })();
  </script>
    
asked by anonymous 24.02.2016 / 15:06

1 answer

5

It's quite tricky to identify when the user has stopped typing, what you can do is put a gap to search for your suggestion.

An example of this would be counting 1 seconds after the keyUp event so if it was 1 seconds without typing a new character you can perform the request and pick up the suggestions.

Example:

var typingTimer; //timer identifier
var doneTypingInterval = 1000; //time in ms, 1 second for example

//on keyup, start the countdown
$('#myInput').keyup(function() {
  clearTimeout(typingTimer);
  if ($('#myInput').val) {
    typingTimer = setTimeout(doneTyping, doneTypingInterval);
  }
});

//user is "finished typing," do something
function doneTyping() {
  console.log('parei de digitar');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><inputtype="text" id="myInput">

More details: Run Javascript Function when User Finishes typing

    
24.02.2016 / 15:24