Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 494
Martin AJ Avatar asked Sep 22 '16 19:09

Martin AJ


Video Answer


1 Answers

You could create a simple throttle mechanism

$("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);

    $(this).data('timer', timer);
});
like image 184
adeneo Avatar answered Sep 30 '22 13:09

adeneo