How can I make a delay to send 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 offers some tags (those that have a matched substring with what the user has written so far) to the user as an autocomplete block when he prints his tags.

What is my problem? My current code sends a new ajax request for every keystroke. For example, if a user writes something, my script sends 9 ajax requests that seem like nightmares.

Anyway, how can I handle this? I mean, do I need to delay sending? Something like "do not send the request until 1 second after the last character inserted"? or is there a better idea?

+4
1

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

Source: https://habr.com/ru/post/1655522/


All Articles