Martin AJ Martin AJ - 2 months ago 7
jQuery Question

How can I make a delay for sending an ajax request?

Here is my code:

$("input").on('keydown', function(){
$.ajax({
url : '/files/tags_autocomplete.php',
dataType : 'JSON',
success : function (tags) {
$("ul").html(tags.output);
}
});
});


My code suggests some tags (the ones that have a matched substring with what the user has written so far) to user as an autocomplete box when he is typing his tags.

What's my problem? My current code sends a new ajax request per each keydown. For example, if the user writes
something
, my script sends 9 ajax requests which seems like a nightmare.

Anyway, how can I handle that? I mean do I need to implement a delay for sending? Something like "don't send the request until 1 sec after last character inserted"? or is there any better idea?

Answer

You could create a simple throttle mechanism that places the ajax request in a timeOut, and if the event is triggered again within a given time, the timeOut is cancelled, and the ajax request isn't sent.
This way, it only sends the ajax request when the user stops typing for whatever amount of time is specified (half a second below (500ms))

$("input").on('keydown', function(){

    clearTimeout( $(this).data('timer') );

    var timer = setTimeout(function() {
      $.ajax({
          url :  '/files/tags_autocomplete.php',
          dataType : 'JSON',
          success : function (tags) {
              $("ul").html(tags.output);
          }
      });
    }, 500); // time to wait

    $(this).data('timer', timer);
});